Home > Backend Development > Python Tutorial > How Can Python's `datetime` Module Help Determine a Date's Day of the Week?

How Can Python's `datetime` Module Help Determine a Date's Day of the Week?

Barbara Streisand
Release: 2024-12-04 03:44:10
Original
181 people have browsed it

How Can Python's `datetime` Module Help Determine a Date's Day of the Week?

How to Determine the Day of the Week for a Given Date

When working with dates, it often becomes necessary to determine the corresponding day of the week. Python's datetime module provides a convenient method to accomplish this task.

Getting the Day of the Week

To retrieve the day of the week from a datetime object, utilize the weekday() method. This method returns an integer representing the day of the week, with Monday being 0 and Sunday being 6.

>>> today = datetime.datetime(2017, 10, 20)
>>> today.weekday()
6
Copy after login

In this example, the output is 6, indicating that October 20, 2017, falls on a Friday.

Example: Retrieving the Day of the Week for Today

The datetime.datetime.today() method provides access to the current date and time. By combining this with weekday(), you can easily determine the day of the week for today:

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2023, 3, 7, 15, 37, 51, 777063)
>>> datetime.datetime.today().weekday()
2
Copy after login

In this case, the output is 2, confirming that March 7, 2023, is a Tuesday.

The above is the detailed content of How Can Python's `datetime` Module Help Determine a Date's Day of the Week?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template