[英]How to iterate from a custom day in the past to today?
我需要遍歷從自定義日期到現在的所有日子。 我需要所有正確的日子,而不僅僅是天數。
例如,我輸入10表示月份,輸入2018表示年份。 我需要得到:
2018-10-01
2018-10-02
...
2018-10-31
2018-11-01
2018-11-02
...
2019-05-21
https://docs.python.org/3.7/library/datetime.html
date = datetime.datetime(2007,12,5)
while date != datetime.date.today():
date += datetime.timedelta(days=1)
print(date)
該示例使用for loop
。 但是,我嘗試使用遞歸。
from datetime import timedelta, date
def getdate(date):
print (date)
if date == date.today(): return
getdate(date+timedelta(1))
start_date = date(2018, 1, 1)
getdate(start_date)
如果要從pandas獲取數據幀 ,則date_range
函數可以為您完成所有工作(doc) 。 pd.datetime.now()
方法為您提供當前日期(doc)
這里舉一個例子:
def get_df_days_to_now(year, month, day = 1):
date_start = "%4d/%d/%d" % (year, month, day)
date_end = pd.datetime.now().strftime("%d/%m/%Y")
return pd.date_range(start=date_start, end=date_end, freq="D")
print(get_df_days_to_now(2019, 5))
# DatetimeIndex(['2019-05-01', '2019-05-02', '2019-05-03', '2019-05-04',
# '2019-05-05', '2019-05-06', '2019-05-07', '2019-05-08',
# '2019-05-09', '2019-05-10', '2019-05-11', '2019-05-12',
# '2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16',
# '2019-05-17', '2019-05-18', '2019-05-19', '2019-05-20',
# '2019-05-21', '2019-05-22'],
# dtype = 'datetime64[ns]', freq = 'D')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.