Python Dates
Python handles dates and times through the built-in datetime module, which lets you create, read, and format points in time.
Working with the datetime module
Python does not have a separate date data type built into the core language, but the standard library includes a module called datetime that provides everything you need. It offers classes such as datetime, date, time, and timedelta for representing moments in time and the gaps between them.
Getting the current date and time
import datetime
now = datetime.datetime.now()
print(now)
# Example output: 2026-07-15 09:42:18.531290
print(now.year) # 2026
print(now.weekday()) # 0 = Monday, 6 = SundayWhen you print a datetime object you see the year, month, day, hour, minute, second, and microsecond. Each of these is also available as an attribute, so you can read individual pieces such as .year or .hour whenever you need them.
Creating a specific date
To build a date yourself, call the datetime constructor with a year, month, and day. The hour, minute, and second are optional and default to zero. This is useful when you need a fixed reference point rather than the current moment.
Building a date and measuring a difference
import datetime
launch = datetime.datetime(2026, 1, 1)
today = datetime.datetime(2026, 7, 15)
gap = today - launch # a timedelta object
print(gap.days) # 195
print(type(gap)) # <class 'datetime.timedelta'>Formatting dates with strftime()
The strftime() method turns a datetime object into a readable string using format codes. Each code is a percent sign followed by a letter that stands for one part of the date, such as the month name or the four-digit year.
Formatting a date as text
import datetime
d = datetime.datetime(2026, 7, 15, 9, 42)
print(d.strftime("%A, %d %B %Y"))
# Output: Wednesday, 15 July 2026
print(d.strftime("%Y-%m-%d %H:%M"))
# Output: 2026-07-15 09:42Exercise: Python Dates
Which module do you import to work with date and time objects in Python?