In this tutorial, we will learn about How to get the day of the week given a date in Python. Python provides an easy way to determine the day of the week, such as Monday, Tuesday, and so on, based on a specific date. In this, we will explore how to accomplish this using Python.
Get the day of the week by a given date in Python
To get the day of the week, we will utilize the datetime
module, which offers functionalities for working with dates and times in Python.
( 1 ) Importing the datetime Module
To begin, we need to import the datetime module, which provides the necessary tools for working with dates:
import datetime
( 2 ) Getting the Day of the Week
Now, let’s define a function called “get_day_of_week” that takes a date as input and returns the corresponding day of the week. Here’s a code implementation:
def get_day_of_week(date):
# Convert the date string to a datetime object
date_obj = datetime.datetime.strptime(date, '%Y-%m-%d')
# Get the day of the week (Monday = 0, Sunday = 6)
day_of_week = date_obj.weekday()
# Map the day of the week to its name
day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][day_of_week]
return day_name
In this function, we first convert the date string into a datetime object using the strptime method. It parses the date based on the specified format. The format ‘%Y-%m-%d’ indicates that the date string should have the format ‘YYYY-MM-DD’.
Next, we obtain the day of the week using the weekday method of the datetime object. It returns an integer where Monday is represented by 0 and Sunday is represented by 6.
Finally, we map the obtained day of the week to its corresponding name using a list and return the name as the result.
( 3 ) By using the inbuilt function
To use the “get_day_of_week” function, simply provide a date in the ‘YYYY-MM-DD’ format as an argument. Here’s an example of usage:
date = '2023-06-27'
day_of_week = get_day_of_week(date)
print(day_of_week)
In this example, the date ‘2023-06-27’ is passed to the get_day_of_week function, and the corresponding day of the week, in this case, “Tuesday,” is printed to the console.
Conclusion
By utilizing the datetime module in Python and following the steps outlined in this guide. We can easily determine the day of the week for any given date. This functionality can be helpful in various applications, such as date calculations, scheduling, and organizing events.
Example:
import datetime
def get_day_of_week(date):
# Convert the date string to a datetime object
date_obj = datetime.datetime.strptime(date, '%Y-%m-%d')
# Get the day of the week (Monday = 0, Sunday = 6)
day_of_week = date_obj.weekday()
# Map the day of the week to its name
day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][day_of_week]
return day_name
# Example usage
date = '2023-06-27'
day_of_week = get_day_of_week(date)
print('Day of the Week is - ',day_of_week)
Output:
Day of the Week is - Tuesday
Find the day of the Week by using isoweekday() method
The isoweekday()
method in Python is a function available in the datetime module that allows you to obtain the day of the week for a specific date, adhering to the ISO weekday convention. Unlike the weekday() method, which assigns Monday as 0 and Sunday as 6, the isoweekday()
method assigns Monday as 1 and Sunday as 7.
By using the isoweekday()
method, you can effortlessly retrieve the day of the week for a given date as an integer ranging from 1 to 7, representing the days Monday to Sunday, respectively.
import datetime
def get_day_of_week(date):
# Convert the date string to a datetime object
date_obj = datetime.datetime.strptime(date, '%Y-%m-%d')
# Get the day of the week using isoweekday()
day_number = date_obj.isoweekday()
# Map the day number to its name
day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
day_name = day_names[day_number - 1]
return day_name
# Example usage
date = '2023-06-27'
day_of_week = get_day_of_week(date)
print("The day of the week for", date, "is", day_of_week + ".")
Output:
The day of the week for 2023-06-27 is Tuesday.
In this example, the “get_day_of_week” function takes a date string in the format ‘YYYY-MM-DD’ as input. It converts the string to a datetime object using the strptime method.
The isoweekday() method is used to retrieve the day of the week as an integer, where Monday is represented by 1 and Sunday by 7.
To map the day number to its corresponding name, a list of day names is created. Since the list is zero-indexed, we subtract 1 from the day number to access the correct index in the list.
Finally, the function returns the day name.
How to get the day of the week by using strftime() method
The strftime()
method in Python is a function available in the datetime module that allows you to format date and time objects into strings. Its name is an abbreviation for “string format time.” The primary purpose of strftime() is to convert a datetime object into a string representation based on a specified format.
The strftime()
method accepts a format string as its argument, which consists of various format codes representing different components of the date and time. These format codes are prefixed with a percent sign (%
) to indicate their special meaning.
Some Format Codes of strftime() Method :
%Y
: Represents the year with century as a four-digit number (e.g., 2023).%m
: Represents the month as a zero-padded decimal number (e.g., 05 for May).%d
: Represents the day of the month as a zero-padded decimal number (e.g., 03).%H
: Represents the hour in 24-hour clock format as a zero-padded decimal number (e.g., 15 for 3 PM).%M
: Represents the minute as a zero-padded decimal number (e.g., 07).%S
: Represents the second as a zero-padded decimal number (e.g., 42).
Using these format codes, we can construct a custom format string to represent the desired date and time format. For example, the format string “%Y-%m-%d %H:%M:%S” will output a date and time string in the format “2023-05-03 15:07:42”.
Additionally, the strftime() method supports other format codes and modifiers. It include textual representations of the day of the week, month names, time zones, and more. We can refer to the Python documentation on strftime() for an exhaustive list of format codes and their meanings.
By utilizing the strftime() function, we have the flexibility to format date and time objects into human-readable strings according to our specific requirements.
Example:
import datetime
def get_day_of_week(date):
# Convert the date string to a datetime object
date_obj = datetime.datetime.strptime(date, '%Y-%m-%d')
# Format the date to retrieve the day of the week
day_of_week = date_obj.strftime('%A')
return day_of_week
# Example usage
date = '2023-06-27'
day_of_week = get_day_of_week(date)
print(f"The day of the week for {date} is {day_of_week}.")
Output:
The day of the week for 2023-06-27 is Tuesday.
The “get_day_of_week” function takes a date string in the format ‘YYYY-MM-DD’ as input. Using the strptime()
method from the datetime module, we convert the date string into a datetime object, allowing us to manipulate and extract information from it.
Next, we employ the strftime() method, which stands for “string format time,” to format the date and retrieve the day of the week. By specifying the format code %A
, we can obtain the full weekday name. For example, if the input date is a Tuesday, the method will return the string “Tuesday.”
Finally, the function returns the day of the week as a string. We demonstrate the usage of this function by providing an example date, ‘2023-06-27’, and storing the result in the “day_of_week” variable. To display the output, we use an f-string to construct a descriptive sentence that states the day of the week for the given date
Get the Day of the Week using Calendar Module
The calendar module in Python provides functionalities for working with dates, months, and calendars. It allows you to generate calendars for a specific month or an entire year, retrieve information about dates, and perform various operations related to calendars.
Below are the key features of the Calendar Module :
- Calendar Generation: The module enables you to generate calendars for a specific month or an entire year. It provides functions like
calendar.month()
andcalendar.calendar()
that produce formatted representations of calendars. - Date Information: You can extract information about specific dates using functions such as
calendar.weekday()
,calendar.monthrange()
, andcalendar.isleap()
. These functions allow you to determine the day of the week, the number of days in a month, and whether a year is a leap year or not. - Iteration and Navigation: The module includes functions like
calendar.itermonthdates()
andcalendar.iterweekdays()
that allow you to iterate over the dates in a month or the weekdays in a week. These functions are useful when you need to perform operations on each date or weekday within a given range. - Formatting and Localization: The
calendar
module provides functions for formatting dates and calendar representations. You can format dates using thecalendar.formatdate()
function, which supports various formatting options. Additionally, the module supports localization by providing functions such ascalendar.setfirstweekday() customizing
the starting day of the week based on local conventions.
Example:
import calendar
def print_calendar(year, month):
# Generate the calendar for the specified year and month
cal = calendar.monthcalendar(year, month)
# Print the calendar
print(calendar.month_name[month], year)
print(calendar.weekheader(3))
for week in cal:
print(week)
# Example usage
year = 2023
month = 6
print_calendar(year, month)
Output:
June 2023
Mon Tue Wed Thu Fri Sat Sun
[0, 0, 0, 1, 2, 3, 4]
[5, 6, 7, 8, 9, 10, 11]
[12, 13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24, 25]
[26, 27, 28, 29, 30, 0, 0]
In this example, we define a function “print_calendar” that takes a year and a month as input. Using the "calendar.monthcalendar()"
function, we generate a two-dimensional list representing the calendar for the specified year and month. Then, we print the month name and year using “calendar.month_name[month]” and the week header using "calendar.weekheader()"
. Finally, we iterate over the calendar and print each week.
The calendar module provides a range of functionalities for working with dates and calendars, making it a useful tool when dealing with time-related operations in Python.