小能豆

在 Python 中创建日期范围

javascript

我想创建一个日期列表,从今天开始,回溯任意天数,例如,在我的示例中为 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

阅读 39

收藏
2024-08-28

共1个答案

小能豆

你的方法很好用,但还有一种更符合 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_rangeend指定periods指定
  • .to_list()DatetimeIndexTimestamp

这两种方法都会为你提供从今天开始并回溯 100 天的日期列表。第一种方法使用datetimepandas方法

2024-08-28