简体   繁体   中英

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. 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

date = datetime.datetime(2007,12,5)
while date != datetime.date.today(): 
    date += datetime.timedelta(days=1)
    print(date) 

The sample uses 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) . The pd.datetime.now() method gives you the current date (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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM