Count Dates in Python

孤者浪人 提交于 2020-01-24 11:38:08

问题


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?


回答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 from module datetime
>>> sum(datetime(year, month, 13).weekday() == 4 
        for year in range(1950, 2051) for month in range(1,13))
174



回答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)
for year in xrange(1950, 2051):
    for month in months:
        if date(year, month, 13).weekday() == 4:
            friday13 += 1



回答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.




回答4:


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

import datetime
print(datetime.datetime(1950,1,13).weekday())



回答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).



来源:https://stackoverflow.com/questions/10168501/count-dates-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!