ZetCode

Python datetime

last modified November 19, 2026 Python 3.15

In this article we work with the datetime module in Python. The module is part of the standard library and provides types for dates, times, and durations.

The module defines these main classes:

This article is an overview. Some topics have their own articles: Python timedelta covers durations, Python format datetime formatting, Python parse dates parsing, and Python zoneinfo time zones with daylight saving time. The examples run with the TZ environment variable set to Europe/Bratislava, so local time is CET or CEST.

Current date and time

The date.today method returns the current local date and datetime.now the current local date and time.

current_datetime.py
from datetime import date, datetime

today = date.today()
now = datetime.now()

print(today)
print(now)
print(repr(today))
print(repr(now))

The print function shows the readable form, which is the ISO 8601 format with a space between the date and the time. The repr function shows how to create the same object in code. The output differs on every run.

$ python current_datetime.py
2026-11-19
2026-11-19 21:11:59.393085
datetime.date(2026, 11, 19)
datetime.datetime(2026, 11, 19, 21, 11, 59, 393085)

Creating dates and times

Most of the time we create objects for specific moments. The constructors take the fields from the largest unit to the smallest.

create_dates.py
from datetime import date, datetime, time

release = date(2026, 11, 19)
alarm = time(6, 45)
meeting = datetime(2026, 11, 19, 14, 30)

print(release)
print(alarm)
print(meeting)

start = datetime.combine(release, alarm)
print(start)

print(meeting.date())
print(meeting.time())

midnight = datetime(2026, 11, 19)
print(midnight)

A time object has no date. The datetime.combine method joins a date and a time into a datetime, and the date and time methods split it again. When we omit the time fields of a datetime, they default to zero, which is midnight.

$ python create_dates.py
2026-11-19
06:45:00
2026-11-19 14:30:00
2026-11-19 06:45:00
2026-11-19
14:30:00
2026-11-19 00:00:00

Invalid values

The constructors check every field. A date that does not exist in the calendar raises ValueError, so a date object is always a valid date.

invalid_values.py
from datetime import date, datetime, time

attempts = [
    lambda: date(2026, 2, 29),
    lambda: date(2028, 2, 29),
    lambda: date(2026, 13, 1),
    lambda: time(24, 0),
    lambda: datetime(2026, 11, 19, 10, 60),
]

for create in attempts:
    try:
        print("ok:", create())
    except ValueError as e:
        print("ValueError:", e)

February 29 exists only in leap years: 2026 is not one, 2028 is. Hours run from 0 to 23 and minutes from 0 to 59. The lambdas delay each call until it runs inside the try block.

$ python invalid_values.py
ValueError: day 29 must be in range 1..28 for month 2 in year 2026
ok: 2028-02-29
ValueError: month must be in 1..12, not 13
ValueError: hour must be in 0..23, not 24
ValueError: minute must be in 0..59, not 60

Fields and weekdays

The fields of a date or time are read-only attributes. Methods compute further values, such as the day of the week.

attributes.py
from datetime import datetime

dt = datetime(2026, 11, 19, 14, 30, 15, 250000)

print(dt.year, dt.month, dt.day)
print(dt.hour, dt.minute, dt.second, dt.microsecond)

print("weekday():", dt.weekday())
print("isoweekday():", dt.isoweekday())

names = ["Monday", "Tuesday", "Wednesday", "Thursday",
         "Friday", "Saturday", "Sunday"]
print(names[dt.weekday()])

print(dt.timetuple().tm_yday)
print(dt.isocalendar())

The weekday method counts from 0 for Monday to 6 for Sunday, while isoweekday counts from 1 to 7, as the ISO 8601 standard does. The tm_yday field of timetuple is the day of the year. The isocalendar method returns the ISO year, week, and weekday; ISO weeks are covered in Python ISO weeks.

$ python attributes.py
2026 11 19
14 30 15 250000
weekday(): 3
isoweekday(): 4
Thursday
323
datetime.IsoCalendarDate(year=2026, week=47, weekday=4)

Replacing fields

Date and time objects are immutable. To change a field, we create a new object with the replace method.

replace_fields.py
import copy
from datetime import date, datetime

meeting = datetime(2026, 11, 19, 14, 30)

moved = meeting.replace(hour=16, minute=0)
print(meeting)
print(moved)

d = date(2026, 11, 19)
print(d.replace(day=1))
print(d.replace(month=1, day=1))
print(copy.replace(d, year=2027))

try:
    meeting.year = 2027
except AttributeError as e:
    print("AttributeError:", e)

try:
    date(2028, 2, 29).replace(year=2027)
except ValueError as e:
    print("ValueError:", e)

The replace method returns a copy with the given fields changed. It is a handy way to get the first day of a month or of a year. Since Python 3.13 the generic copy.replace function does the same. Assigning to an attribute raises AttributeError, and replace raises ValueError when the new date does not exist, as February 29 in 2027.

$ python replace_fields.py
2026-11-19 14:30:00
2026-11-19 16:00:00
2026-11-01
2026-01-01
2027-11-19
AttributeError: attribute 'year' of 'datetime.date' objects is not writable
ValueError: day 29 must be in range 1..28 for month 2 in year 2027

Comparing and sorting

Dates and times support the comparison operators, so we can sort them and pass them to min and max.

compare_dates.py
from datetime import date, datetime

deadlines = {
    "report": date(2026, 12, 4),
    "invoice": date(2026, 11, 30),
    "review": date(2026, 11, 24),
    "backup": date(2026, 12, 1),
}

today = date(2026, 11, 25)

for task, due in sorted(deadlines.items(), key=lambda item: item[1]):
    state = "overdue" if due < today else "open"
    print(f"{due}  {task:8} {state}")

print("first:", min(deadlines.values()))
print("last:", max(deadlines.values()))

print(date(2026, 11, 19) == datetime(2026, 11, 19))

try:
    print(date(2026, 11, 19) < datetime(2026, 11, 19, 12))
except TypeError as e:
    print("TypeError:", e)

A later date is greater than an earlier one. The tasks are sorted by their due date and those before today are marked as overdue. Although datetime is a subclass of date, the two are not mixed in comparisons: equality is False and ordering raises TypeError. Convert one side first, for example with the date method.

$ python compare_dates.py
2026-11-24  review   overdue
2026-11-30  invoice  open
2026-12-01  backup   open
2026-12-04  report   open
first: 2026-11-24
last: 2026-12-04
False
TypeError: '<' not supported between instances of 'datetime.date' and 'datetime.datetime'

Date arithmetic

Subtracting two dates gives a timedelta, and adding a timedelta to a date gives a new date.

date_arithmetic.py
from datetime import date, datetime, timedelta

start = date(2026, 11, 19)
end = date(2026, 12, 24)

diff = end - start
print(diff)
print(type(diff).__name__, diff.days)

print(start + timedelta(days=30))
print(start - timedelta(weeks=2))

departure = datetime(2026, 11, 19, 22, 40)
flight = timedelta(hours=9, minutes=35)
print("arrival:", departure + flight)

try:
    print(start + end)
except TypeError as e:
    print("TypeError:", e)

There are 35 days between November 19 and Christmas Eve. The days attribute gives the number as an integer. Adding a flight time to a departure crosses midnight correctly. Adding two dates has no meaning and raises TypeError. Durations, their normalization, and their pitfalls are covered in Python timedelta.

$ python date_arithmetic.py
35 days, 0:00:00
timedelta 35
2026-12-19
2026-11-05
arrival: 2026-11-20 08:15:00
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'datetime.date'

Ordinals and ranges of days

Each date has an ordinal, the number of days since January 1 of year 1. The module has no range function for dates, but adding one day in a loop produces a range.

day_range.py
from datetime import date, timedelta

d = date(2026, 11, 19)
print(d.toordinal())
print(date.fromordinal(d.toordinal() + 100))

print(date.min, date.max)

start = date(2026, 11, 26)
end = date(2026, 12, 6)

day = start
while day <= end:
    if day.weekday() < 5:
        print(day.strftime("%a %d %b"))
    day += timedelta(days=1)

count = (end - start).days + 1
weekdays = sum(1 for i in range(count)
               if (start + timedelta(days=i)).weekday() < 5)
print("working days:", weekdays)

The toordinal and fromordinal methods convert between dates and day numbers. Dates range from year 1 to year 9999. The loop prints the working days between two dates; the generator expression counts them without printing.

$ python day_range.py
739939
2027-02-27
0001-01-01 9999-12-31
Thu 26 Nov
Fri 27 Nov
Mon 30 Nov
Tue 01 Dec
Wed 02 Dec
Thu 03 Dec
Fri 04 Dec
working days: 7

Formatting

The isoformat method produces ISO 8601 strings and strftime custom formats. A format specification in an f-string calls strftime as well.

format_dates.py
from datetime import datetime

dt = datetime(2026, 11, 19, 14, 30, 5)

print(str(dt))
print(dt.isoformat())
print(dt.isoformat(sep=" ", timespec="minutes"))
print(dt.date().isoformat())

print(dt.strftime("%d.%m.%Y %H:%M"))
print(dt.strftime("%A, %B %d, %Y"))
print(dt.strftime("%I:%M %p"))

print(f"{dt:%Y-%m-%d}")
print(f"{dt:%a %d %b}")

The sep and timespec parameters control the separator and the precision of isoformat. In the format strings, %d, %m, and %Y are the day, month, and year, %A and %B the weekday and month names, and %I with %p the 12-hour clock. All the directives are listed in Python format datetime.

$ python format_dates.py
2026-11-19 14:30:05
2026-11-19T14:30:05
2026-11-19 14:30
2026-11-19
19.11.2026 14:30
Thursday, November 19, 2026
02:30 PM
2026-11-19
Thu 19 Nov

Parsing

The fromisoformat method parses ISO 8601 strings, while strptime parses any format described with the same directives as strftime.

parse_dates.py
from datetime import date, datetime

print(date.fromisoformat("2026-11-19"))
print(datetime.fromisoformat("2026-11-19T14:30:05"))
print(datetime.fromisoformat("2026-11-19 14:30"))

dt = datetime.strptime("19.11.2026 14:30", "%d.%m.%Y %H:%M")
print(dt)

d = date.strptime("Nov 19, 2026", "%b %d, %Y")
print(d)

try:
    datetime.strptime("2026/11/19", "%Y-%m-%d")
except ValueError as e:
    print("ValueError:", e)

The fromisoformat method accepts a space instead of the T and omitted seconds. The date.strptime method, new in Python 3.14, returns a date directly. When the string does not match the format, strptime raises ValueError. See Python parse dates for more.

$ python parse_dates.py
2026-11-19
2026-11-19 14:30:05
2026-11-19 14:30:00
2026-11-19 14:30:00
2026-11-19
ValueError: time data '2026/11/19' does not match format '%Y-%m-%d'

Naive and aware datetimes

A datetime without a tzinfo is naive: it does not say which time zone it belongs to. An aware datetime carries a time zone and represents a single moment.

naive_aware.py
from datetime import UTC, datetime, timedelta, timezone

naive = datetime(2026, 11, 19, 14, 30)
utc = datetime(2026, 11, 19, 13, 30, tzinfo=UTC)
new_york = timezone(timedelta(hours=-5), "EST")
ny = datetime(2026, 11, 19, 8, 30, tzinfo=new_york)

for dt in (naive, utc, ny):
    print(dt, dt.tzinfo, dt.utcoffset())

print(utc == ny)
print(ny.astimezone(UTC))

try:
    print(naive < utc)
except TypeError as e:
    print("TypeError:", e)

print(naive.replace(tzinfo=UTC))

The UTC constant, added in Python 3.11, is an alias for timezone.utc. A timezone object is a fixed offset; the offset of -5 hours prints as -1 day, 19:00:00 because negative durations are normalized to whole negative days. Aware datetimes compare as moments, so 13:30 UTC equals 8:30 EST. Comparing a naive datetime with an aware one raises TypeError. The replace method attaches a time zone without converting the time.

$ python naive_aware.py
2026-11-19 14:30:00 None None
2026-11-19 13:30:00+00:00 UTC 0:00:00
2026-11-19 08:30:00-05:00 EST -1 day, 19:00:00
True
2026-11-19 13:30:00+00:00
TypeError: can't compare offset-naive and offset-aware datetimes
2026-11-19 14:30:00+00:00

The deprecated utcnow

Older code calls datetime.utcnow to get the current UTC time. The method returns a naive datetime, which most functions then take as local time.

utcnow_deprecated.py
from datetime import UTC, datetime

old = datetime.utcnow()
print(old.tzinfo)

now = datetime.now(UTC)
print(now.tzinfo)

print(datetime.now().astimezone().tzinfo)

Since Python 3.12, utcnow and utcfromtimestamp issue a DeprecationWarning. Use datetime.now(UTC), which returns an aware datetime. Calling astimezone without an argument converts to the local time zone and attaches it as a fixed offset.

$ python utcnow_deprecated.py
/home/user/python/utcnow_deprecated.py:3: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
  old = datetime.utcnow()
None
UTC
CET

Timestamps

A Unix timestamp is the number of seconds since 1970-01-01 00:00 UTC. The fromtimestamp method converts it to a datetime and the timestamp method back.

timestamps.py
from datetime import UTC, datetime

ts = 1_795_000_000
print(datetime.fromtimestamp(ts, tz=UTC))
print(datetime.fromtimestamp(ts))
print(datetime.fromtimestamp(ts).astimezone())

aware = datetime(2026, 11, 19, 13, 30, tzinfo=UTC)
print(aware.timestamp())

naive = datetime(2026, 11, 19, 13, 30)
print(naive.timestamp())

print(datetime.fromtimestamp(0, tz=UTC))

With tz=UTC we get an aware datetime in UTC. Without it, the result is a naive datetime in local time, one hour ahead in November in Bratislava. The timestamp method treats a naive datetime as local time, so the same wall time gives a timestamp that is 3600 seconds smaller than the UTC one. Prefer aware datetimes when converting.

$ python timestamps.py
2026-11-18 11:06:40+00:00
2026-11-18 12:06:40
2026-11-18 12:06:40+01:00
1795095000.0
1795091400.0
1970-01-01 00:00:00+00:00

Converting between time zones

The astimezone method converts an aware datetime to another time zone. Real time zones with daylight saving time come from the zoneinfo module.

convert_zones.py
from datetime import datetime
from zoneinfo import ZoneInfo

call = datetime(2026, 11, 19, 16, 0, tzinfo=ZoneInfo("Europe/Bratislava"))

cities = ["America/New_York", "Asia/Tokyo", "Australia/Sydney", "UTC"]

print(f"{'Europe/Bratislava':20} {call:%a %H:%M %Z}")
for name in cities:
    local = call.astimezone(ZoneInfo(name))
    print(f"{name:20} {local:%a %H:%M %Z}")

The call is scheduled at 16:00 in Bratislava. The %Z directive prints the abbreviation of each zone; in Tokyo and Sydney the call is already on Friday. The Python zoneinfo article covers daylight saving time, ambiguous times, and arithmetic across transitions.

$ python convert_zones.py
Europe/Bratislava    Thu 16:00 CET
America/New_York     Thu 10:00 EST
Asia/Tokyo           Fri 00:00 JST
Australia/Sydney     Fri 02:00 AEDT
UTC                  Thu 15:00 UTC

Age and next birthday

The last example combines the parts of the article. It computes the age of people and the number of days until their next birthday.

age.py
from datetime import date


def age(born, today):
    years = today.year - born.year
    if (today.month, today.day) < (born.month, born.day):
        years -= 1
    return years


def birthday_in(year, born):
    try:
        return born.replace(year=year)
    except ValueError:
        return date(year, 3, 1)


def next_birthday(born, today):
    nxt = birthday_in(today.year, born)
    if nxt < today:
        nxt = birthday_in(today.year + 1, born)
    return nxt


today = date(2026, 11, 19)
people = {
    "Lucia": date(1990, 11, 19),
    "Peter": date(1985, 12, 2),
    "Anna": date(2004, 2, 29),
    "Tomas": date(2000, 1, 15),
}

for name, born in people.items():
    nxt = next_birthday(born, today)
    days = (nxt - today).days
    print(f"{name:6} {age(born, today):3}  next {nxt}  in {days:3} days")

The age is the difference of the years, minus one if this year's birthday has not come yet; comparing (month, day) tuples decides that. Subtracting dates and dividing by 365 would be wrong around birthdays because of leap years. A birthday on February 29 does not exist in most years, so replace raises ValueError and we celebrate on March 1 instead. Lucia has her birthday today.

$ python age.py
Lucia   36  next 2026-11-19  in   0 days
Peter   40  next 2026-12-02  in  13 days
Anna    22  next 2027-03-01  in 102 days
Tomas   26  next 2027-01-15  in  57 days

Source

datetime – Basic date and time types

In this article we have worked with dates, times, and datetimes in Python. See also Python timedelta, Python format datetime, Python parse dates, Python zoneinfo, Python calendar, and Python time module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.