Work with Dates and Times in Python

Learn how to create, compare, and manipulate dates, times, and timedeltas using Python's datetime module.

7 min read

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.

pythonpython
from datetime import date
 
today = date.today()
print(today)                               # 2026-07-12
print(today.year, today.month, today.day)  # 2026 7 12

date.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.

pythonpython
from datetime import date
 
release = date(2026, 12, 1)
print(release)              # 2026-12-01
print(release.weekday())    # 1
print(release.isoformat())  # 2026-12-01

date(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:

pythonpython
from datetime import date
 
holiday = date.fromisoformat("2026-07-04")
print(holiday)  # 2026-07-04

date.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.

pythonpython
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 5

datetime.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:

pythonpython
from datetime import datetime
 
meeting = datetime(2026, 8, 15, 10, 30)
print(meeting)  # 2026-08-15 10:30:00

The 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.

pythonpython
from datetime import date, timedelta
 
today = date.today()
 
print(today + timedelta(weeks=1))  # 2026-07-19
print(today - timedelta(days=3))   # 2026-07-09

timedelta(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:

pythonpython
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.123456

timedelta 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:

pythonpython
from datetime import date
 
start = date(2026, 7, 1)
end = date(2026, 7, 12)
print((end - start).days)  # 11

The 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.

pythonpython
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.

pythonpython
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:00

replace 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.

pythonpython
from datetime import time
 
lunch = time(12, 30)
closing = time(18, 0)
 
print(lunch.hour)       # 12
print(closing > lunch)  # True

time(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.

pythonpython
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

Rune AI

Key Insights

  • Use datetime.date.today() for the current date and datetime.datetime.now() for the current date and time.
  • Access individual components with .year, .month, .day, .hour, .minute, .second.
  • Use timedelta to 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.
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between date and datetime?

A `date` object holds year, month, and day. A `datetime` object holds year, month, day, hour, minute, second, and microsecond. Use `date` when you only care about the calendar date and `datetime` when you need the time of day too.

How do I get the current date and time?

Use `datetime.date.today()` for the current date or `datetime.datetime.now()` for the current date and time. You can also use `datetime.datetime.today()` which is similar to `now()` but does not accept a time zone argument.

How do I add or subtract days from a date?

Create a `timedelta` object with the `days` argument, then add or subtract it from a date. For example, `date.today() + timedelta(days=7)` gives you the date one week from today.

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.