How do you loop through an entire year showing each day's date?

You are dealing with date objects so it is best to use module datetime ...

import datetime

# pick a year
year = 2006

# create date objects
begin_year = datetime.date(year, 1, 1)
end_year = datetime.date(year, 12, 31)
one_day = datetime.timedelta(days=1)

print "These are all the dates of %d:" % year
next_day = begin_year
for day in range(0, 366):  # includes potential leap year
    if next_day > end_year:
        break
    print next_day
    # increment date object by one day
    next_day += one_day

Thanks, that works well. Now I need a hint, how do I check if the day is a Friday?

Hi Ene, looks like you are working on Friday the 13th project. It took me a while, but I solved it. I can give you a hint, replace the line

print next_day

with this expanded line

print next_day, "day of week =", next_day.weekday()

The week starts with Monday = 0 that means Friday = 4
Have fun!

Thanks Henri,

I needed not only the day of the week, but also the day of the month, so I searched the Python code snippets and found an old snippet from vegaseat called "Date and Time handling in Python" at:
http://www.daniweb.com/code/snippet218.html

He talks about the timetuple, and this tuple contains both data. So I put this in the days of year loop:

# timetuple = (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)
    day_of_month = next_day.timetuple()[2]
    day_of_week = next_day.timetuple()[6]
    # Friday is 4th day of the week
    if day_of_week == 4 and day_of_month == 13:
        print next_day

and it works. My first real project! Smooth!

OK Ene,
pretty smooth! I used

if next_day.weekday() == 4 and next_day.day == 13:

after reading through help("datetime")

How did you know my first name was Henri?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.