Python基于N天生成日期



下面的代码是一个列表推导式,包含了上下边界之间所有可能的日期:

from datetime import date, timedelta
d1 = date(2022,1,1)
d2 = date(2022,12,31)
dates = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]

然而,不提及d2;我想提到我想要生成的n天数:

from datetime import date, timedelta
d1 = date(2022,1,1)
n = 3
dates = []

dates:

2022-01-01
2022-01-02
2022-01-03

您可以创建for-loop并使用timedelta生成日期并将其存储在列表中。

>>> [d1+timedelta(days=i) for i in range(n)]
[datetime.date(2022, 1, 1),
datetime.date(2022, 1, 2),
datetime.date(2022, 1, 3)]
>>> [(d1+timedelta(days=i)).strftime('%Y-%m-%d') for i in range(n)]
['2022-01-01', '2022-01-02', '2022-01-03']

解释:

from datetime import date, timedelta
d1 = date(2022,1,1)
n = 3
dates = []
for i in range(n):
tmp = d1 + timedelta(days=i)
dates.append(tmp.strftime('%Y-%m-%d'))

# Or store as <class 'datetime.date'>
# dates.append(tmp)
print(dates)
输出:

['2022-01-01', '2022-01-02', '2022-01-03']

easy:

from datetime import date, timedelta
N_DAYS = 30
d1 = date(2022,1,1)
d2 = d1+ timedelta(days=N_DAYS)
dates = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]
converted_data = list(map(lambda date:date.strftime('%Y-%m-%d'),dates))
print(converted_data)

如果你不介意使用外部库,pandas.date_range是非常简单和通用的:

import pandas as pd
d1 = '2022-1-1'
# or 
# d1 = datetime.date(2022,1,1)
n = 3
out = pd.date_range(d1, periods=n, freq='D').strftime('%Y-%m-%d').to_list()

输出:['2022-01-01', '2022-01-02', '2022-01-03']

相关内容

  • 没有找到相关文章

最新更新