📜  在Python创建日期范围列表

📅  最后修改于: 2022-05-13 01:55:10.286000             🧑  作者: Mango

在Python创建日期范围列表

给定一个日期,任务是编写一个Python程序来创建一个日期范围列表,其中包含从当前日期开始的下 K 个日期。

例子:

方法 #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)))


输出:

方法 #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)))

输出: