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.
from datetime import date, datetime, timedelta d = date(2030, 3, 15) print(d + timedelta(days=30)) # 2030-04-14
Try it
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.
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()andutcfromtimestamp()are deprecated since Python 3.12 because they return naive objects. Usedatetime.now(timezone.utc)anddatetime.fromtimestamp(ts, tz=timezone.utc).- Subtracting dates gives a
timedelta.timedelta.daysis only the day part; for a total usetotal_seconds(). Negative durations normalize oddly:timedelta(hours=-5)prints as-1 day, 19:00:00. - Adding months is not built in.
timedeltahas no months or years. Usereplace()carefully (it fails on 31 February) or a library such asdateutil. - 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.ZoneInfofor real regions with daylight saving time;timezoneonly handles fixed offsets. Seezoneinfo. strftimecodes can be platform dependent for locale-specific names (%A,%B,%c), andstrptimeis 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+5isTrue. - Valid range is years 1 to 9999.
Related
time,calendar,zoneinfo,ValueError- Lessons: Dates and times, String formatting