遇到一個場景需要獲得一段時間的日期,覺得datetime寫起來不夠explicit, 如下绪妹。
start_date = datetime.datetime.today()
date_list = [start_date - datetime.timedelta(days=x) for x in range(0, days_num)]
然后找了一下乞巧,發(fā)現(xiàn)有很多好用的方法(時間庫)祷杈,記錄一下
- pandas.date_range
import pandas as pd
datelist = pd.date_range(pd.datetime.today(), periods=100).tolist()
- dateutil.rrule
rrule可計算出兩個datetime對象間相差的年月日等時間數(shù)量。
from dateutil import rrule
from datetime import datetime
list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))
- matplotlib.dates.drange
from matplotlib.dates import drange
import datetime
base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)
- dateutil.relativedelta
import datetime as dt
from dateutil.relativedelta import relativedelta
def month_range(start_date, n_months):
for m in range(n_months):
yield start_date + relativedelta(months=+m)
- arrow.Arrow.range()
這個庫還有floor方法很好用
from arrow.Arrow import range
date_range = range('hour',datetime_start, datatime_end)
這個庫用的人較少谴餐,但也很神奇姻政,文檔也很好看
import pendulum
start = pendulum.datetime(2000, 1, 1)
end = pendulum.datetime(2000, 1, 10)
date_range = pendulum.period(start, end).range('days')
參考: