Python Datetime

Beginner
9 min read
Updated: Nov 2026
3 examples
Dates and times

Definition and Usage

The datetime module is Python's standard library for dates, clock times, and durations. Nothing to install: import a class, build an object such as datetime(2024, 3, 15, 10, 30), then compare, subtract, format, or parse it.

Every object is immutable: replace() and astimezone() return a new object. The Datetime Methods index lists every guide, such as now(), strftime(), and strptime().

Python Syntax

Import the classes you need by name. This is the style used in every example on this site:

Python
from datetime import date, datetime, time, timedelta, timezone

day = date(2024, 3, 15)                        # a calendar day
clock = time(10, 30)                           # a clock time
moment = datetime.combine(day, clock)          # 2024-03-15 10:30:00
later = moment + timedelta(days=1, hours=2)    # arithmetic with durations
aware = moment.replace(tzinfo=timezone.utc)    # attach a time zone
print(later, aware.isoformat())
The module and the class share a name.

After import datetime, write datetime.datetime.now(). After from datetime import datetime, write datetime.now(). Mixing the two styles in one file causes AttributeError.

The Six Classes

ClassHoldsExample
dateYear, month, daydate(2024, 3, 15)
timeHour, minute, second, microsecond, optional tzinfotime(10, 30, 45)
datetimeA date and a time together; a subclass of datedatetime(2024, 3, 15, 10, 30)
timedeltaA duration stored as days, seconds, and microsecondstimedelta(hours=36)
tzinfoAbstract base class for time zone rulesSubclass it, or use timezone
timezoneA ready-made tzinfo with a fixed UTC offsettimezone(timedelta(hours=5, minutes=30))

For real zones with daylight saving rules, Python 3.9+ adds zoneinfo (on Windows it needs the tzdata package), so these examples use fixed offsets.

Naive vs Aware Objects

A datetime is aware when its tzinfo returns an offset from utcoffset(); it names one exact instant. It is naive when tzinfo is None: just a wall-clock reading in an unknown zone.

timestamp(), astimezone(), and fromtimestamp() without tz treat naive values as the machine's local time, so results differ between computers. Store aware UTC values and convert only for display. Subtracting or ordering naive against aware raises TypeError; == returns False.

Format Codes Cheat Sheet

Used by strftime() and strptime(). The last column shows the result for datetime(2024, 3, 15, 9, 5, 7, 42000, tzinfo=timezone(timedelta(hours=5, minutes=30))) with the default C/English locale:

CodeMeaningResult
%YYear with century2024
%yYear without century, 2 digits24
%mMonth, 2 digits03
%dDay of the month, 2 digits15
%HHour, 24-hour clock09
%IHour, 12-hour clock09
%pAM or PM (locale)AM
%MMinute05
%SSecond07
%fMicrosecond, 6 digits042000
%aWeekday, short name (locale)Fri
%AWeekday, full name (locale)Friday
%bMonth, short name (locale)Mar
%BMonth, full name (locale)March
%jDay of the year, 3 digits075
%wWeekday number, Sunday is 05
%UWeek of the year, Sunday first10
%WWeek of the year, Monday first11
%zUTC offset as +HHMM (empty if naive)+0530
%ZTime zone name (empty if naive)UTC+05:30
%%A literal percent sign%

%a, %A, %b, %B, and %p follow the locale. Avoid platform-only codes such as %-d and %#d.

ISO 8601 Text and Epoch Timestamps

ISO 8601 writes the biggest unit first, 2024-03-15T10:30:00+05:30, so it sorts correctly as text. isoformat() writes it and fromisoformat() reads it back.

A POSIX timestamp counts seconds since 1970-01-01 00:00:00 UTC: 1710498645 is 2024-03-15 10:30:45 UTC. timestamp() returns it as a float; fromtimestamp(ts, tz=timezone.utc) turns it back. Divide JavaScript milliseconds by 1000 first.

Common Mistakes

MistakeDo this instead
Calling utcnow() or utcfromtimestamp()Both are deprecated since Python 3.12 and return naive values. Use datetime.now(timezone.utc) and datetime.fromtimestamp(ts, tz=timezone.utc).
Storing naive local timesA naive value breaks when a server moves or daylight saving changes. Store aware UTC values or ISO 8601 text with an offset.
Using replace(tzinfo=...) to convertreplace() only relabels the clock reading. Use astimezone(tz) to convert.
Expecting English names everywhere%a, %b, and %p follow the locale. Use numeric codes or ISO 8601 for machine-readable text.
Reading delta.seconds as the totalIt is only the part below one day. Use total_seconds() for the whole duration.

Python Examples

Fixed values only, so the output is the same on every machine.

Example 1 — Attach a Zone and See Why Mixing Fails

Make a naive value aware, then subtract one from the other.

Python
from datetime import datetime, timezone

naive = datetime(2024, 3, 15, 9, 15)
aware = naive.replace(tzinfo=timezone.utc)
print(naive.tzinfo, aware.tzinfo)
print(aware)
try:
    print(aware - naive)
except TypeError:
    print("naive and aware values do not mix")

How It Works

  1. No zone yet. Built without tzinfo, the first value reports None.
  2. Label the clock. replace(tzinfo=timezone.utc) declares 09:15 to be UTC, hence the +00:00 suffix.
  3. Subtraction refuses. A known instant minus an unknown one raises TypeError, caught by except.

Example 2 — Parse Text, Format It, and Round-Trip ISO 8601

Parse a string, print it in a friendlier layout, and round-trip ISO 8601 text.

Python
from datetime import datetime

text = "2024-03-15 10:30"
moment = datetime.strptime(text, "%Y-%m-%d %H:%M")
print(moment.strftime("%d %b %Y, %H:%M"))
print(moment.isoformat())
print(datetime.fromisoformat(moment.isoformat()) == moment)

How It Works

  1. Pattern in, object out. strptime() matches each code against the text.
  2. Friendly display. %b gives Mar in the default C/English locale.
  3. Lossless storage. fromisoformat() turns isoformat() text back into an equal value.

Example 3 — Add Days, Count Days, and Read Calendar Numbers

Add a duration, count days to a holiday, get a timestamp, and read weekday numbers.

Python
from datetime import date, datetime, timedelta, timezone

start = date(2024, 3, 15)
print(start + timedelta(days=30))
print((date(2024, 12, 25) - start).days)
print(datetime(2024, 3, 15, tzinfo=timezone.utc).timestamp())
print(start.weekday(), start.isoweekday(), start.isocalendar()[1])

How It Works

  1. Date plus duration. Thirty days roll over the month end to 14 April.
  2. Date minus date. The resulting timedelta's .days counts 285 days to Christmas.
  3. Seconds since 1970. Midnight UTC that day is 1710460800 seconds after the epoch.
  4. Three numbering systems. Friday is 4 for weekday(), 5 for isoweekday(), in ISO week 11.

Next: Python Datetime Methods by Group

Frequently Asked Questions

The standard library module for dates and times. Its classes date, time, datetime, timedelta, tzinfo, and timezone let you create, compare, format, parse, and do arithmetic with dates.
An aware datetime has a tzinfo with a UTC offset, so it marks one exact instant. A naive one has no offset, and ordering or subtracting it against an aware value raises TypeError.
After import datetime, the name datetime is the module, so you write datetime.datetime.now(). After from datetime import datetime, it is the class, so you write datetime.now().
No. utcnow() and utcfromtimestamp() are deprecated since Python 3.12. Use datetime.now(timezone.utc) and datetime.fromtimestamp(ts, tz=timezone.utc) for aware UTC values.
strftime() or isoformat() write text; strptime() or fromisoformat() parse it. ISO 8601 text such as 2024-03-15T10:30:00+05:30 is the safest format to store.

Browse every datetime method

Open the method index for categorized guides with examples and FAQs.

Datetime Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful