Search code examples
pythondatecalendar

Count Dates in Python


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?


Solution

  • 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