In this tutorial, we will learn how to find the name of the day from a date in Python. With the help of Python’s built-in functions and modules, we can easily extract the day name from a given date.
The beauty of Python lies in its powerful libraries that simplify numerous complex tasks, in this case, the datetime library!
Step 1: Importing Necessary Libraries
In order to find the day’s name from a particular date, we need to import Python’s built-in ‘datetime’ module. The datetime module has a method named weekday() that returns the day of the week as an integer (Monday is 0 and Sunday is 6).
1 |
import datetime |
Step 2: Create a datetime object
We proceed by defining a date as an object of the datetime class. Let’s use the 24th of December, 2005 as an example (in the format of Year, Month, Day).
1 |
date = datetime.datetime(2005, 12, 24) |
Step 3: Finding out the Day Number
Now, by applying the weekday() method to our date object, we get the day number (remember that Monday is 0, Tuesday is 1, and so on).
1 |
day_number = date.weekday() |
Step 4: Creating a Day’s Name List
Next, let’s create a list that represents the names of the days of the week. We can then use this list to match the day number obtained in the previous step to its corresponding day name.
1 |
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] |
Step 5: Extracting the Day Name from the Date
The final step is to extract the day name from the list of “days” using the day number. Remember that list indexing in Python starts from 0.
1 |
day_name = days[day_number] |
The Full Python Code
1 2 3 4 5 6 7 8 |
import datetime date = datetime.datetime(2005, 12, 24) day_number = date.weekday() days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] day_name = days[day_number] print(day_name) |
Output of the Code
Saturday
Conclusion
And that’s it! You now know how to find out the day’s name from any given date using Python. It’s very simple and efficient with Python’s built-in datetime library. This can be very useful in many scenarios, especially when dealing with date-based data while analyzing or preprocessing in data science projects.