Dates and times
Dates are trickier than they look. Months have 28 to 31 days, every fourth year or so has a February 29, and a week from December 28 is in another year. The standard library's datetime module knows all of that. Its most used part is a type that is also called datetime, so programs usually start with from datetime import datetime: from the module datetime, import the type datetime.
Making a datetime
A datetime value holds one moment: a date and a time of day. You make one by giving the year, the month and the day, and if you like, the hour and the minute:
from datetime import datetime
moon_landing = datetime(1969, 7, 20, 20, 17)
print(moon_landing)
new_year = datetime(2027, 1, 1)
print(new_year)
1969-07-20 20:17:00
2027-01-01 00:00:00Without a time, the moment is midnight, 00:00:00. Printed, a datetime shows the year first, then the month and the day, then the hours, minutes and seconds: the international standard order, which sorts correctly as text too.
The parts of a datetime
A datetime stores its parts as attributes, values you reach with a dot and their name: year, month, day, hour, minute and second. They're stored values, not functions, so there are no parentheses after them. The method weekday() does have parentheses: it calculates the day of the week, 0 for Monday up to 6 for Sunday.
from datetime import datetime
meeting = datetime(2026, 11, 3, 14, 30)
print("Year:", meeting.year)
print("Month:", meeting.month)
print("Day:", meeting.day)
print(f"Time: {meeting.hour}:{meeting.minute}")
print("Weekday:", meeting.weekday())
Year: 2026
Month: 11
Day: 3
Time: 14:30
Weekday: 1November 3, 2026 is a Tuesday, day 1 when Monday is day 0.
Only real dates
A datetime can only hold a date that exists. Ask for one that doesn't, and Python stops with a ValueError that says what's wrong:
from datetime import datetime
deadline = datetime(2026, 2, 30)
Traceback (most recent call last):
File "main.py", line 3, in <module>
deadline = datetime(2026, 2, 30)
ValueError: day 30 must be in range 1..28 for month 2 in year 2026That makes it a handy checker: with try and except ValueError, a program can find out whether a date a user typed exists.
The current time
datetime.now() gives the moment it's called, the date and time on the computer's clock. Its output is different every second, so the examples and checks on this site use fixed dates instead. On your own computer, try:
from datetime import datetime
print(datetime.now())