📜  python date get day - Python (1)

📅  最后修改于: 2023-12-03 14:45:57.044000             🧑  作者: Mango

Python Date Get Day

In Python, you can easily retrieve the day of the week from a given date. This can be useful in many cases, such as when you need to schedule tasks based on the day of the week.

Retrieve Day of the Week

To retrieve the day of the week from a given date, you need to use the weekday() method of the date class in the datetime module. This method returns an integer representing the day of the week, where Monday is 0 and Sunday is 6.

Here's a code snippet that demonstrates how to use the weekday() method:

from datetime import date

# Create a date object
d = date(2021, 9, 30)

# Get the day of the week
day_of_week = d.weekday()

# Print the day of the week (0 = Monday, 6 = Sunday)
print(day_of_week)

Output:

3

In this example, we created a date object representing September 30, 2021. We then called the weekday() method to retrieve the day of the week, which is Thursday (represented by the integer 3).

Retrieve Day Name

If you want to retrieve the name of the day of the week (e.g. "Monday", "Tuesday", etc.), you can use the strftime() method of the date class to format the date string.

Here's a modified code snippet that demonstrates how to retrieve the name of the day of the week:

from datetime import date

# Create a date object
d = date(2021, 9, 30)

# Get the day name
day_name = d.strftime("%A")

# Print the day name
print(day_name)

Output:

Thursday

In this example, we used the %A format code to retrieve the full name of the day of the week. You can use other format codes to retrieve different parts of the date, such as the month name or the year.

Conclusion

Retrieving the day of the week from a given date is a simple task in Python, thanks to the built-in weekday() and strftime() methods. By using these methods, you can easily schedule tasks or perform other time-sensitive operations based on the day of the week.