Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Math, Data and Text

The datetime module

Reference for Python's datetime module: date, time, datetime, timedelta and timezone objects, formatting with strftime, parsing, arithmetic and common traps.

The datetime module provides classes for working with calendar dates, clock times and the differences between them. The four you use most are date (year, month, day), time (hour, minute, second, microsecond), datetime (both together) and timedelta (a length of time). A fifth, timezone, represents a fixed offset from UTC.

Objects come in two flavors. A naive object has no time zone information, so it means "some local time". An aware object carries a tzinfo and refers to one exact moment. Mixing the two in comparisons or subtraction raises TypeError. All of these objects are immutable: operations return new objects.

Python
from datetime import date, datetime, timedelta

d = date(2030, 3, 15)
print(d + timedelta(days=30))   # 2030-04-14

Try it

Python Creating, formatting and parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Arithmetic, time zones and traps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Main classes

Class Purpose
date(year, month, day) A calendar date in the Gregorian calendar.
time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) A time of day, independent of any date.
datetime(year, month, day, hour=0, ...) A date and a time.
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) A duration. Stored as days, seconds and microseconds.
timezone(offset, name=None) A fixed UTC offset; timezone.utc is UTC itself.

Useful methods and attributes

Member What it does
datetime.now(tz=None) The current local time; pass timezone.utc for an aware UTC value.
date.today() Today's local date.
datetime.strptime(text, format) Parses text with a format string. Raises ValueError if it does not match.
obj.strftime(format) Formats an object as text using codes such as %Y, %m, %d, %H, %M, %S, %A, %B.
obj.isoformat() / fromisoformat() ISO 8601 text, for example 2030-03-15T14:30:05.
obj.replace(**fields) A copy with some fields changed.
datetime.astimezone(tz) Converts an aware datetime to another zone (a naive one is assumed to be system local time).
weekday() / isoweekday() Day of week as 0-6 (Monday=0) or 1-7 (Monday=1).
timedelta.total_seconds() The whole duration as a float number of seconds.

Usage notes

  • utcnow() and utcfromtimestamp() are deprecated since Python 3.12 because they return naive objects. Use datetime.now(timezone.utc) and datetime.fromtimestamp(ts, tz=timezone.utc).
  • Subtracting dates gives a timedelta. timedelta.days is only the day part; for a total use total_seconds(). Negative durations normalize oddly: timedelta(hours=-5) prints as -1 day, 19:00:00.
  • Adding months is not built in. timedelta has no months or years. Use replace() carefully (it fails on 31 February) or a library such as dateutil.
  • Naive and aware objects cannot be compared or subtracted. Pick one convention; storing and calculating in UTC and converting only for display is the safest.
  • Use a zoneinfo.ZoneInfo for real regions with daylight saving time; timezone only handles fixed offsets. See zoneinfo.
  • strftime codes can be platform dependent for locale-specific names (%A, %B, %c), and strptime is slowish; for ISO strings, fromisoformat() is faster and, since Python 3.11, accepts most ISO 8601 forms.
  • Equality across zones compares the instant: 12:00 UTC == 17:00 UTC+5 is True.
  • Valid range is years 1 to 9999.