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:
Always import from the module first. The class name and the module name are the same, which trips people up:
What will be the output?
Once you have a date object you can read its parts back out as plain integers:
What will be the output?
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:
What will be the output?
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:
What will be the output?
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:
What will be the output?
What will be the output?
What will be the output?
What will be the output?