Count Dates In Python
Solution 1:
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 frommodule datetime
>>>sum(datetime(year, month, 13).weekday() ==4foryearinrange(1950, 2051) formonthinrange(1,13))
174
Solution 2:
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)
foryearin xrange(1950, 2051):
formonthin months:
if date(year, month, 13).weekday() ==4:
friday13 +=1
Solution 3:
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.
Solution 4:
Sounds like homework. Hint (weekday 4 is a Friday):
import datetime
print(datetime.datetime(1950,1,13).weekday())
Solution 5:
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).
Post a Comment for "Count Dates In Python"