我想创建一个日期列表,从今天开始,回溯任意天数,例如,在我的示例中为 100 天。有没有比这更好的方法?
import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList
你的方法很好用,但还有一种更符合 Python 风格、更简洁的方法,即使用列表推导来实现相同的结果。下面是优化版本
import datetime numdays = numdays = numdays = numdays num 100 dateList = [datetime.datetime.today() - datetime.timedelta(days=x) dateList = [datetime.datetime.today() - datetime.timedelta(days=x) dateList = [datetime.datetime.today() - datetime.timedelta(days=x dateList = [datetime.datetime.today() - datetime.timedelta(days dateList = [datetime.datetime.today() - datetime.timedelta dateList = [datetime.datetime.today() - datetime dateList = [datetime.datetime.today() - dateList = [datetime.datetime.today() dateList = [datetime.datetime.today dateList = [datetime.datetime dateList = [datetime dateList = [ dateList = dateList date for x in range(numdays)] print(dateList) ``
append
range(numdays)
numdays-1
pandas
如果你经常使用日期和时间,你可以考虑使用这个pandas库,
import pandas as pd numdays = numdays = num 100 dateList = pd.date_range(end=pd.Timestamp.today(), periods=numdays).to_list() dateList = pd.date_range(end=pd.Timestamp.today(), periods=numdays).to_list dateList = pd.date_range(end=pd.Timestamp.today(), periods=numdays).to dateList = pd.date_range(end=pd.Timestamp.today(), periods=numdays). dateList = pd.date_range(end=pd.Timestamp.today(), periods=numdays dateList = pd.date_range(end=pd.Timestamp.today(), periods=num dateList = pd.date_range(end=pd.Timestamp.today(), periods dateList = pd.date_range(end=pd.Timestamp.today(), dateList = pd.date_range(end=pd.Timestamp.today dateList = pd.date_range(end=pd.Timestamp dateList = pd.date_range(end=pd dateList = pd.date_range(end dateList = pd.date_range dateList = pd.date dateList = pd dateList = dateList date print(dateList)
pd.date_range
end
periods
.to_list()
DatetimeIndex
Timestamp
这两种方法都会为你提供从今天开始并回溯 100 天的日期列表。第一种方法使用datetime是pandas方法
datetime