To return the day of the week from a string, you have to import the datetime module and run this code:
1 2 3 |
from datetime import datetime print(datetime.strptime('March 7, 2020', '%B %d, %Y').strftime('%A')) |
It will return the day of the week:
Saturday
Let’s analyze the code:
1 |
datetime.strptime('March 7, 2020', '%B %d, %Y') |
The strptime function creates a datetime object from the string. The string has to be in a certain format.
The next part of the code returns a string representation of a date. In this case, it’s a day.
1 |
strftime('%A') |
You can also use the lowercase letter, like this:
1 |
strftime('%a') |
This time it’s going to return day in the abbreviated form.
Sat
The weekday function
The next way, you can return the day of the week is the weekday function. It will use the same module: datetime. For this method, you have to use a different approach.
1 2 3 |
from datetime import datetime print(datetime.strptime('March 7, 2020', '%B %d, %Y').weekday()) |
First, we are going to return the number of the day of the week. in our case, it’s 5.
1 2 3 4 5 6 7 |
from datetime import datetime week_days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") my_date = datetime.strptime('March 7, 2020', '%B %d, %Y') day_name = week_days[my_date.weekday()] print(day_name) |
The result is the sith position of the tuple:
Saturday
It’s especially useful if you want to use custom names for the days or use names in different languages.