TGIF (Programming) – 30


Friday is the best day of the week, and so I really want to know how many Fridays there are in this file. But, with a twist. I want to know how many Fridays there are one year later than each date.


We need to parse and modify the data, then simply count how many Fridays there are.


import datetime
import calendar

n_fridays = 0

with open('date.txt', 'r') as f:
    for date in f.readlines():
        date = date.rstrip()

        date = datetime.datetime.strptime(date, "%B %d, %Y")
        if not calendar.isleap(date.year) or != 29:
            date = date.replace(year = date.year + 1)
            if date.weekday() == FRIDAY:
                n_fridays += 1


We needed to include a check for not leap year or day not 29, because we ran into the issue where the date + 1 year did not exist, which happened when both of those conditions were true. Hence, filtering them out gives us our correct result.



Comments are closed.

Up ↑