📅  最后修改于: 2023-12-03 15:04:04.830000             🧑  作者: Mango
Have you ever needed to determine what day of the week a certain date falls on? With Python, it's easy to get the day of the week from a given date. In this article, we'll explore the various ways to implement this functionality.
The datetime
module in Python provides classes for working with dates and times. Specifically, the datetime
class provides a method called weekday()
that returns an integer representing the day of the week (0 for Monday, 1 for Tuesday, and so on). Here's an example of how to use this method:
import datetime
date_string = "2022-09-22" # Year, month, day
date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
weekday = date.weekday()
print(weekday) # Outputs: 3 (Thursday)
In this example, we create a datetime
object from a string using the strptime()
method. We then call the weekday()
method on the resulting object to get the day of the week, which is printed to the console.
Besides the datetime
module, Python also has a module called calendar
that provides various functions for working with calendars. In particular, the weekday()
function in this module returns the same integer representing the day of the week as the weekday()
method in the datetime
class. Here's an example that demonstrates the use of calendar.weekday()
:
import calendar
date_string = "2022-09-22" # Year, month, day
year, month, day = map(int, date_string.split("-"))
weekday = calendar.weekday(year, month, day)
print(weekday) # Outputs: 3 (Thursday)
In this example, we first use the split()
method to separate the year, month, and day values from the input string. We then pass these values to the calendar.weekday()
function to get the day of the week.
These are just two of the many ways to get the day of the week from a date in Python. Regardless of which method you choose, the ability to extract this information from a given date can be useful in a variety of applications.