-1

I want to iterate all the days in a given year: so it will generate a datetime object for the 1st of January, through all the other days (including Feb 29 - if it exists for that year) to the 31st of December.

How can I do this ?

I was trying this:

from datetime import datetime
start_date = datetime( 2015, 1, 1 )
start_date = startdate + 1

But then realized you can't just add one (one what?) like this- you have to add on a timedelta (of one day) to do this.

monojohnny
  • 5,894
  • 16
  • 59
  • 83
  • 2
    Have you tried anything at all? – Morgan Thrapp Sep 10 '15 at 16:35
  • 1
    @MorganThrapp don't act as this is something straight forward in Python, it isn't, closest thing he **could've** found (which I don't consider "timedelta") is `someDatetime.replace(day=someDatetime.day+someNumber)` which a) throws `day is out of range for month` if `someNumber` is too high instead of automatically increasing the month and overflowing b) is super unintuitively named , if this'd be JavaScript, then OK, but here ........ – jave.web Feb 11 '21 at 16:22

1 Answers1

2
from datetime import datetime, timedelta

def gen_days( year ):
    start_date=datetime( year, 1, 1 )
    end_date=datetime( year, 12, 31 )
    d=start_date
    dates=[ start_date ]
    while d < end_date:
        d += timedelta(days=1)
        dates.append( d )
    return dates

if __name__=='__main__':
    d=gen_days( 2015 )
    print len(d)
    d2=gen_days( 2016 ) # leap year
    print len(d2)

Sorry - was going to post some non-working code with my question, but I got it working more quickly than I thought (with help from this and others : How to increment the day in datetime? Python)

Community
  • 1
  • 1
monojohnny
  • 5,894
  • 16
  • 59
  • 83