True or False: Friday the 13th?

Spooky fun with Python and Datetime

Face of a black cat
Photo by Hannah Troupe on Unsplash

It appears that Halloween and all its fun accouterments will be downsized this year in my neighborhood. However, in the spirit of the season I tried out this challenge from edabit.com :

Given the month and year as numbers, return whether that month contains a Friday 13th.

Datetime and all its associated classes have been a sore spot of mine, so this felt like a perfect challenge to learn in a fun way. I decided to try solving the challenge in 2 different ways: strptime() and strftime(). What’s the difference? Strptime (or string parsed time) is used to convert a string to a datetime object. Strftime (or string from time) is used to convert a time to a string.

To solve using string parsed time, I started by importing datetime and calendar. The function parameters are the integer month and year, so I created a string using the month and year (the day is “13”). Then I used datetime.strptime() to convert the string to a datetime object, and used the weekday function to determine the day of the week. The 0 is Monday and 6 is Saturday. That integer is then used with the calendar module to convert the integer to the day, which is then compared to “Friday”. Here’s my code:

And I tried out the supplied examples:

results from the 3 examples
results from the 3 examples
The results of Friday the Thirteen

To solve using string from time, I again needed to import datetime and from datetime date. In my first version I used a string date as the input parameter and used a format code (%A is the directives’ weekday as a full name) to compare to “Friday”:

Then I refactored the code to accept the month and year as integers:

After more refactoring, the function became a one-liner!

(And the same results as above — 2 Trues and 1 False.)