In Python, there are multiple approaches to obtain the current day of the week, each offering its own advantages.
- Using the weekday() method from the datetime module, which returns the day of the week as an integer, allowing for easy mapping to day names.
- Another method utilizes the strftime() method, enabling direct formatting of a datetime object into a string representation of the day of the week.
While the former provides flexibility in handling day names through integer values, the latter offers a more concise solution by directly formatting the date object.
Method 1 – Using datetime module
You can use the datetime module in Python to get the current day of the week.
Let’s see a simple code snippet to achieve that.
import datetime # Get the current date current_date = datetime.datetime.now() # Get the day of the week (0 = Monday, 1 = Tuesday, ..., 6 = Sunday) day_of_week = current_date.weekday() # Convert the day of the week to a string days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] current_day_of_week = days[day_of_week] print("Today is:", current_day_of_week)
Now I’ll explain the above code in detail:
- Import the datetime module to work with dates and times.
- Get the current date and time using datetime.datetime.now().
- Use the weekday() method to get the day of the week as an integer (0 for Monday, 1 for Tuesday, etc.).
- Create a list of day names.
- Retrieve the day name corresponding to the integer obtained in step 3.
- Print the current day of the week.
Method 2 – Using strftime() method
Let’s explore another method to get the current day of the week is by using the strftime() method available in the datetime module. This method allows you to format a datetime object into a string representation according to a specified format.
You can use the %A format specifier to retrieve the full name of the day of the week.
The example code is below:
import datetime # Get the current date current_date = datetime.datetime.now() # Format the current date to retrieve the full name of the day of the week current_day_of_week = current_date.strftime("%A") print("Today is:", current_day_of_week)
Let me summarize the key points from the above example.
- Import the datetime module to work with dates and times.
- Get the current date and time using datetime.datetime.now().
- Use the strftime() method to format the current_date object into a string representation.
- Pass “%A” as the format specifier to strftime(). %A represents the full name of the day of the week.
- Store the formatted string (the full name of the day of the week) in the variable current_day_of_week.
- Print the current day of the week.
This method directly formats the date object into the desired string representation, eliminating the need for additional logic to map integers to day names as in the previous method.
It’s easy to understand.