[英]How to iterate from a custom day in the past to today?
I need to iterate through all the days from a custom day to now. 我需要遍历从自定义日期到现在的所有日子。 I need all the correct day not just the count of the days. 我需要所有正确的日子,而不仅仅是天数。
For example, I enter 10 for month and 2018 for year. 例如,我输入10表示月份,输入2018表示年份。 I need to get: 我需要得到:
2018-10-01
2018-10-02
...
2018-10-31
2018-11-01
2018-11-02
...
2019-05-21
How to increment a datetime by one day? 如何将日期时间增加一天?
https://docs.python.org/3.7/library/datetime.html 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)
The sample uses for loop
. 该示例使用for loop
。 But, I try to use recursion. 但是,我尝试使用递归。
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)
If you want to get a dataframe from pandas , the date_range
function does all the work for you (doc) . 如果要从pandas获取数据帧 ,则date_range
函数可以为您完成所有工作(doc) 。 The pd.datetime.now()
method gives you the current date (doc) pd.datetime.now()
方法为您提供当前日期(doc)
Here one example: 这里举一个例子:
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.