1

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
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Casper
  • 1,663
  • 7
  • 35
  • 62
  • Start here: https://stackoverflow.com/questions/3240458/how-to-increment-a-datetime-by-one-day – smac89 May 21 '19 at 23:34
  • Possible duplicate of [Iterating through a range of dates in Python](https://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python) – drec4s May 21 '19 at 23:36
  • Possible duplicate of [Print all day-dates between two dates](https://stackoverflow.com/questions/7274267/print-all-day-dates-between-two-dates) – smac89 May 21 '19 at 23:41

3 Answers3

1

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) 
ohlr
  • 1,839
  • 1
  • 13
  • 29
1

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)
yaho cho
  • 1,779
  • 1
  • 7
  • 19
  • recursion is more expansive then iteration + you might incur a `maximum recursion depth exceeded` error. So I would not agree that it is necessarily the better code. https://www.quora.com/In-Python-which-is-more-efficient-to-use-recursion-or-iteration – ohlr May 29 '19 at 20:48
  • @ohlr Thank you for the advice. I agree with you that it is not the better code. But, I think Recursive code could be good style to reduce side effect and to make simple code. – yaho cho Jun 05 '19 at 15:01
0

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')
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40