Count Dates in Python

Question:

I am trying to count the number of Friday the 13ths per year from 1950-2050 using Python (I know, a little late). I am not familiar with any date/calendar packages to use. Any thoughts?

Asked By: mike

||

Answers:

Is it some kind of exercise or homework? I faintly remember of having solved it. I can give you a hint, I seem to have used Calendar.itermonthdays2 Of course there should be other ways to solve it as well.

Answered By: Senthil Kumaran

Sounds like homework. Hint (weekday 4 is a Friday):

import datetime
print(datetime.datetime(1950,1,13).weekday())
Answered By: Mark Tolonen

the datetime.date class has a weekday() function that gives you the day of the week (indexed from 0) as an integer, so Friday is 4. There’s also isoweekday() that indexes days from 1, it’s up to you which you prefer.

Anyway, a simple solution would be:

friday13 = 0
months = range(1,13)
for year in xrange(1950, 2051):
    for month in months:
        if date(year, month, 13).weekday() == 4:
            friday13 += 1
Answered By: Endophage

This has a direct solution. Use sum to count the number of times where the 13th of the month is a Friday:

>>> from datetime import datetime # the function datetime from module datetime
>>> sum(datetime(year, month, 13).weekday() == 4 
        for year in range(1950, 2051) for month in range(1,13))
174
Answered By: Raymond Hettinger

While other solutions are clear and simple, the following one is more “calendarist”. You will need the dateutil package, which is installable as a package:

from datetime import datetime
from dateutil import rrule

fr13s = list(rrule.rrule(rrule.DAILY,
                         dtstart=datetime(1950,1,13),
                         until=datetime(2050,12,13),
                         bymonthday=[13],
                         byweekday=[rrule.FR]))
# this returns a list of 174 datetime objects

You see these five arguments of rrule.rrule: Take every rrule.DAILY (day) between dtstart and until where bymonthday is 13 and byweekday is rrule.FR (Friday).

Answered By: eumiro
from datetime import *
from time import strptime
yil = input("yilni kiritnig:: ")
kun1 = "01/01/"+yil
kun1 = datetime.strptime(kun1, "%d/%m/%Y")
while 1:
    if kun1.strftime("%A") == "Friday":
        break
    kun1 = kun1 + timedelta(days=1)
count = 0
while 1:
    if int(kun1.strftime("%Y")) == int(yil)+1:
        break
    if kun1.strftime("%d") == "13":
        count+=1
    kun1=kun1+timedelta(days=7)
print(count)
Answered By: Shohida Abdullayeva
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.