在Python创建日期范围列表
给定一个日期,任务是编写一个Python程序来创建一个日期范围列表,其中包含从当前日期开始的下 K 个日期。
例子:
Input : test_date = datetime.datetime(1997, 1, 4), K = 5
Output : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)]
Explanation : 5 dates after 4 January are extracted in list.
Input : test_date = datetime.datetime(1997, 1, 4), K = 4
Output : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0)]
Explanation : 4 dates after 4 January are extracted in list.
方法 #1:使用timedelta() +列表理解
在这种情况下,我们可以使用 timedelta() 将连续的增量添加到 day,并且使用列表理解来迭代所需的大小并构建所需的结果。
Python3
# Python3 code to demonstrate working of
# Get Construct Next K dates List
# Using timedelta() + list comphehension
import datetime
# initializing date
test_date = datetime.datetime(1997, 1, 4)
# printing original date
print("The original date is : " + str(test_date))
# initializing K
K = 5
# timedelta() gets successive dates with
# appropriate difference
res = [test_date + datetime.timedelta(days=idx) for idx in range(K)]
# printing result
print("Next K dates list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Get Construct Next K dates List
# Using count() + generator function
import datetime
import itertools
# initializing date
test_date = datetime.datetime(1997, 1, 4)
# printing original date
print("The original date is : " + str(test_date))
# initializing K
K = 5
# timedelta() gets successive dates with
# appropriate difference
gen_fnc = (
test_date - datetime.timedelta(days=idx) for idx in itertools.count())
# islice passes counter
res = itertools.islice(gen_fnc, K)
# printing result
print("Next K dates list : " + str(list(res)))
输出:
The original date is : 1997-01-04 00:00:00
Next K dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0),
datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)]
方法 #2:使用count() +生成器函数
在此,我们执行与上述函数类似的任务,使用生成器执行日期连续任务。
蟒蛇3
# Python3 code to demonstrate working of
# Get Construct Next K dates List
# Using count() + generator function
import datetime
import itertools
# initializing date
test_date = datetime.datetime(1997, 1, 4)
# printing original date
print("The original date is : " + str(test_date))
# initializing K
K = 5
# timedelta() gets successive dates with
# appropriate difference
gen_fnc = (
test_date - datetime.timedelta(days=idx) for idx in itertools.count())
# islice passes counter
res = itertools.islice(gen_fnc, K)
# printing result
print("Next K dates list : " + str(list(res)))
输出:
The original date is : 1997-01-04 00:00:00
Next K dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 3, 0, 0),
datetime.datetime(1997, 1, 2, 0, 0), datetime.datetime(1997, 1, 1, 0, 0), datetime.datetime(1996, 12, 31, 0, 0)]