Reputation: 23811
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?
Upvotes: 2
Views: 5866
Reputation: 1
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)
Upvotes: 0
Reputation: 226316
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
Upvotes: 7
Reputation: 212885
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).
Upvotes: 0
Reputation: 21473
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
Upvotes: 4
Reputation: 177674
Sounds like homework. Hint (weekday 4 is a Friday):
import datetime
print(datetime.datetime(1950,1,13).weekday())
Upvotes: 0
Reputation: 56841
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.
Upvotes: 0