The datetime module in the Python standard library lets you create, compare, and manipulate dates and times. You can get the current date, count the days until an event, add weeks to a deadline, or check whether one date comes before another.
The module provides three main types: date for calendar dates, time for the time of day, and datetime for both together. A fourth type, timedelta, represents a duration between two points in time.
from datetime import date
today = date.today()
print(today) # 2026-07-12
print(today.year, today.month, today.day) # 2026 7 12date.today() returns the current date as a date object. The year, month, and day are available as plain integer attributes, so you can use them directly in any calculation.
Creating date objects
Create a specific date by passing the year, month, and day to the date constructor, always in that order. Like the rest of the Python standard library, the date class is available the moment you import it.
from datetime import date
release = date(2026, 12, 1)
print(release) # 2026-12-01
print(release.weekday()) # 1
print(release.isoformat()) # 2026-12-01date(2026, 12, 1) creates December 1, 2026. The weekday method returns 1, which means Tuesday, because Monday is 0 and Sunday is 6. The isoformat method returns the standard YYYY-MM-DD string form of the date.
You can also go the other way and build a date from an ISO-formatted string:
from datetime import date
holiday = date.fromisoformat("2026-07-04")
print(holiday) # 2026-07-04date.fromisoformat parses any string in YYYY-MM-DD form. It raises a ValueError if the string is not a valid calendar date.
Working with datetime objects
A datetime object stores both the date and the time of day, down to microseconds.
from datetime import datetime
now = datetime.now()
print(now) # 2026-07-12 14:30:05.123456
print(now.hour, now.minute, now.second) # 14 30 5datetime.now() returns the current local date and time. On top of the date attributes, you also get hour, minute, second, and microsecond as integers.
Create a specific datetime the same way, with a required date part and an optional time part:
from datetime import datetime
meeting = datetime(2026, 8, 15, 10, 30)
print(meeting) # 2026-08-15 10:30:00The year, month, and day are required. Hour, minute, second, and microsecond all default to zero when you leave them out, which is why the meeting lands at exactly 10:30:00.
Date arithmetic with timedelta
Use timedelta to add or subtract a duration from a date or datetime.
from datetime import date, timedelta
today = date.today()
print(today + timedelta(weeks=1)) # 2026-07-19
print(today - timedelta(days=3)) # 2026-07-09timedelta(weeks=1) represents a duration of 7 days, so adding it moves the date one week ahead. Subtracting timedelta(days=3) gives the date three days ago.
You can combine several duration arguments in a single call:
from datetime import datetime, timedelta
now = datetime.now()
offset = timedelta(days=2, hours=6, minutes=30)
print(now + offset) # 2026-07-14 21:00:05.123456timedelta accepts days, hours, minutes, seconds, milliseconds, microseconds, and weeks. Internally it stores everything as days, seconds, and microseconds.
Subtraction works too. When you subtract one date from another, the result is a timedelta describing the gap between them:
from datetime import date
start = date(2026, 7, 1)
end = date(2026, 7, 12)
print((end - start).days) # 11The days attribute of the resulting timedelta gives you the gap as a plain integer, which is exactly what you want for countdowns and age calculations.
Comparing dates and times
Date, datetime, and time objects all support the standard comparison operators, and earlier moments compare as less than later ones.
from datetime import date
deadline = date(2026, 8, 1)
today = date.today()
if today < deadline:
print("Deadline is still ahead.") # Deadline is still ahead.
elif today == deadline:
print("Deadline is today.")
else:
print("Deadline has passed.")The same logic works for datetime objects, where the time of day breaks ties between two values that fall on the same calendar day. Because comparisons behave naturally, you can also sort a list of dates with sorted or find the earliest one with min, without writing any custom logic.
Modifying dates with replace
Dates and datetimes are immutable, so you never change one directly. To get a new object with some fields changed, call replace.
from datetime import datetime
now = datetime.now()
start_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
print(now) # 2026-07-12 14:30:05.123456
print(start_of_month) # 2026-07-01 00:00:00replace returns a new datetime with the fields you named changed and every other field kept as it was. This is the usual way to normalize a timestamp to the start of a day, month, or year.
Working with time objects
A time object stores only the time of day, with no date attached. It suits recurring times such as store hours or alarm settings.
from datetime import time
lunch = time(12, 30)
closing = time(18, 0)
print(lunch.hour) # 12
print(closing > lunch) # Truetime(12, 30) represents 12:30 PM. Time objects support the same comparison operators as dates and datetimes, which is why the closing time compares as greater than the lunch time.
Practical example: days until an event
This function combines date construction, subtraction, and the days attribute into a reusable countdown.
from datetime import date
def days_until(year, month, day):
target = date(year, month, day)
remaining = (target - date.today()).days
if remaining > 0:
return f"{remaining} days until {target}."
if remaining == 0:
return f"{target} is today."
return f"{target} was {-remaining} days ago."
print(days_until(2026, 12, 25)) # 166 days until 2026-12-25.The function builds the target date, subtracts today, and reads the days attribute from the resulting timedelta. Once you can build and compare dates as objects, the next step is usually displaying them nicely, which is covered in format dates and times in Python.
Common mistakes
Three mistakes trip up almost everyone who starts with this module.
Using the wrong import. The module is named datetime and it contains a class also named datetime. Write from datetime import datetime to get the class directly, or spell out datetime.datetime(2026, 7, 12) if you imported only the module.
Assuming months have 30 days. timedelta has no months argument because months vary in length. To shift by months, use replace and handle year rollover yourself, or use the third-party dateutil library.
Confusing weekday and isoweekday. The weekday method returns 0 for Monday through 6 for Sunday, while isoweekday returns 1 for Monday through 7 for Sunday. Pick one convention and stick with it.
Rune AI
Key Insights
- Use
datetime.date.today()for the current date anddatetime.datetime.now()for the current date and time. - Access individual components with
.year,.month,.day,.hour,.minute,.second. - Use
timedeltato add or subtract days, hours, minutes, or weeks from a date. - Compare dates using standard operators like
<,>,==. - Call
.replace()to create a new date or datetime with specific components changed. - Use
.isoformat()for a standard string representation.
Frequently Asked Questions
What is the difference between date and datetime?
How do I get the current date and time?
How do I add or subtract days from a date?
Conclusion
The datetime module is the standard way to handle dates and times in Python. Start with date for calendar work, datetime when you need time-of-day precision, and timedelta for date arithmetic. When you need to display dates to users or parse date strings, move on to the strftime and strptime methods.
More in this topic
Format Dates and Times in Python
Learn how to use strftime and strptime to format dates as strings and parse date strings into Python datetime objects.
What Is the Python Standard Library?
Learn what the Python standard library is, why it matters, and how to use its built-in modules without installing anything extra.
Encode and Decode Base64 Data in Python
Learn how to use Python's base64 module to encode binary data as text and decode Base64 strings back to bytes.