Datetime

Dates and datetimes

Working with calendar values as plain text breaks the moment you try to sort or compare them. Python ships a datetime module so dates behave like real dates. This lesson covers the date and datetime classes, their attributes, and how to grab the current moment.


Storing dates as plain strings like '2024-07-04' breaks fast. You can't sort them safely, compare them, or compute the gap between two dates. Python ships a datetime module so dates behave like real dates.

Import the date class and create one. The arguments are year, month, day, in that order:

Python
Output

Always import from the module first. The class name and the module name are the same, which trips people up:

Python

What will be the output?

Python

Once you have a date object you can read its parts back out as plain integers:

Python
Output

What will be the output?

Python

A datetime is a date plus a time of day. The first three arguments work just like date. After that you can add hour, minute, and second.

Build a datetime for March 15, 2025 at 9:30 AM:

Python
Output

What will be the output?

Python

To grab the current moment you don't pass any arguments. datetime.now() returns the current datetime, date.today() returns just today's date.

These functions read your computer's clock:

Python
Output

What will be the output?

Python

The .weekday() method tells you what day of the week a date falls on. Monday is 0, Tuesday is 1, all the way to Sunday which is 6.

July 4, 2024 fell on a Thursday:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python