Back to Home 20 lessons Pyodide ready

Python Datetime
Dates, Times & Timezones

Master Python's datetime module: date and time objects, arithmetic with timedelta, formatting with strftime, parsing with strptime, and timezone-aware code. 20 interactive lessons with runnable code β€” crafted by @PoeticGlenn.

What you will learn

Everything about Python's datetime module β€” the standard way to represent and manipulate dates and times. Learn date, time, datetime, and timedelta objects; date arithmetic; formatting with strftime() and parsing with strptime(); ISO 8601 strings; working with timezones and UTC; and the differences between naive and aware datetimes. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.

Why Dates and Times Are Deceptively Hard

Dates and times seem simple β€” until you hit timezones, daylight saving time, leap years, and ambiguous parsing. Python's datetime module (part of the standard library) provides a clean, powerful toolkit for handling all of this correctly. Whether you're logging events, calculating ages, scheduling tasks, or displaying timestamps to users, mastering datetime is essential. This curriculum, designed by @PoeticGlenn, walks you through every component of the module β€” from basic objects to timezone-aware arithmetic β€” with hands-on, runnable code.

Date & Time

Represent points in time with date, time, and datetime objects.

Arithmetic

Add or subtract days, hours, and seconds with timedelta β€” no manual math.

Timezones

Work with UTC and local timezones safely using timezone.utc and zoneinfo.

"Time is the only currency that never refunds. Python's datetime helps you spend it wisely." β€” @PoeticGlenn 🐍

Every Application Has a Clock

Timestamps appear in every log file, every database row, every user session. Whether you're building a scheduler, a chat app, a data pipeline, or a simple report, you'll work with dates and times. This curriculum, curated by @PoeticGlenn, ensures you handle them correctly β€” including the tricky edge cases that cause bugs in production.

πŸ“… Logging & Monitoring

Record when events happen. Compare timestamps to measure durations and detect anomalies.

πŸ›’ E-commerce

Calculate shipping dates, expiration times, and user ages. Handle timezone differences.

🌍 Global Apps

Show local times to users worldwide. Convert between timezones safely.

πŸ“Š Data Analysis

Resample time series, bucket events by date, and compute rolling windows.

@PoeticGlenn says: "Master datetime once, save hours debugging timestamps forever."

The Standard for Time in Python

Python's datetime module is the foundation for time handling across the ecosystem. Django's ORM uses it for all model fields. Pandas builds its powerful DatetimeIndex on top of it. dateutil, pytz, and zoneinfo extend it. Web frameworks, logging libraries, and schedulers all rely on it. Learning datetime as taught by @PoeticGlenn gives you a skill that's used in literally every Python project.

Standard Library

No install needed. Part of Python since 2.3, refined in Python 3.

Ecosystem Standard

Django, pandas, FastAPI, SQLAlchemy, and every major library uses it.

Correct by Default

Handles leap years, month lengths, and DST transitions correctly.

"Every moment is a timestamp waiting to be formatted β€” learn to do it right."

πŸ“… Date Objects β€” Working with Years, Months, Days

Represent calendar dates without a time component.

πŸ“ 1.1 Creating a date

The date class represents a calendar date (year, month, day).

Step-by-step explanation:

  • Step 1: Import date from datetime.
  • Step 2: Create with date(2026, 6, 30).
  • Step 3: Access .year, .month, .day.
python
from datetime import date

d = date(2026, 6, 30)
print("Date:", d)
print("Year: ", d.year)
print("Month:", d.month)
print("Day:  ", d.day)

# Today's date
today = date.today()
print("\nToday:", today)
print("Weekday (0=Mon):", today.weekday())
print("ISO weekday (1=Mon):", today.isoweekday())
πŸ’‘ weekday() returns 0 for Monday; isoweekday() returns 1 for Monday. Use whichever fits your logic.

πŸ“ 1.2 Date Arithmetic with timedelta

Add or subtract days, weeks, or months (via timedelta) from dates.

Step-by-step explanation:

  • Step 1: Create a date.
  • Step 2: Add a timedelta(days=7) for next week.
  • Step 3: Subtract to go backwards.
python
from datetime import date, timedelta

start = date(2026, 1, 15)
print("Start:", start)

next_week = start + timedelta(days=7)
print("+7 days:", next_week)

prev_week = start - timedelta(days=7)
print("-7 days:", prev_week)

# Difference between dates gives timedelta
diff = next_week - start
print("Difference:", diff)
print("Days:", diff.days)
✨ date arithmetic is calendar-aware β€” it handles month lengths and leap years automatically.

πŸ“ 1.3 Parsing from ISO String

Use date.fromisoformat() to parse YYYY-MM-DD strings.

Step-by-step explanation:

  • Step 1: Pass an ISO 8601 string.
  • Step 2: Get a date object back.
  • Step 3: Use .isoformat() to go the other way.
python
from datetime import date

# Parse ISO 8601 string
d = date.fromisoformat("2026-06-30")
print("Parsed:", d)
print("Type:  ", type(d).__name__)

# Serialize back
print("ISO:   ", d.isoformat())

# Invalid strings raise ValueError
try:
    date.fromisoformat("30/06/2026")
except ValueError as e:
    print("\nError:", e)
⚠️ fromisoformat() only accepts the exact format YYYY-MM-DD. For other formats, use strptime().

⏰ Time Objects β€” Hours, Minutes, Seconds

Represent a time-of-day without a date.

πŸ“ 2.1 Creating a time

The time class stores hour, minute, second, microsecond, and optional timezone.

Step-by-step explanation:

  • Step 1: Import time from datetime.
  • Step 2: Create with time(14, 30, 15).
  • Step 3: Access fields individually.
python
from datetime import time

t = time(14, 30, 15, 500000)
print("Time:", t)
print("Hour:       ", t.hour)
print("Minute:     ", t.minute)
print("Second:     ", t.second)
print("Microsecond:", t.microsecond)

# Different constructors
print("\nDefault:", time())
print("Hourly: ", time(hour=9))
print("Full:   ", time(23, 59, 59))

πŸ“ 2.2 Comparing Times

Times can be compared directly with <, >, ==.

Step-by-step explanation:

  • Step 1: Create two time objects.
  • Step 2: Use comparison operators.
  • Step 3: Note that comparison is lexicographic (hour β†’ minute β†’ second).
python
from datetime import time

morning = time(9, 0)
noon = time(12, 0)
evening = time(18, 30)

print("morning < noon:  ", morning < noon)
print("noon < evening:  ", noon < evening)
print("morning == 9:00: ", morning == time(9, 0))

# Sort times
times = [evening, morning, noon]
print("\nSorted:", sorted(times))

πŸ“† Datetime Objects β€” The Full Package

Combine date and time into a single datetime object.

πŸ“ 3.1 Creating a datetime

The most-used class in the module β€” holds both date and time.

Step-by-step explanation:

  • Step 1: Import datetime from the datetime module.
  • Step 2: Create with year, month, day, hour, minute, second.
  • Step 3: Use now() for the current local datetime.
python
from datetime import datetime

# Explicit constructor
dt = datetime(2026, 6, 30, 14, 30, 45)
print("Datetime:", dt)
print("Date part:", dt.date())
print("Time part:", dt.time())

# Current local time
now = datetime.now()
print("\nNow:", now)

# Current UTC time
utc_now = datetime.utcnow()
print("UTC now:", utc_now, "(naive, no tz info)")
⚠️ utcnow() is deprecated in Python 3.12+. Use datetime.now(timezone.utc) instead β€” see Section 6.

πŸ“ 3.2 Extracting Components

A datetime exposes all date and time fields.

Step-by-step explanation:

  • Step 1: Create a datetime.
  • Step 2: Access fields via attributes.
  • Step 3: Use isocalendar() for ISO year/week/day.
python
from datetime import datetime

dt = datetime(2026, 6, 30, 14, 30, 45, 123456)

print("Year:        ", dt.year)
print("Month:       ", dt.month)
print("Day:         ", dt.day)
print("Hour:        ", dt.hour)
print("Minute:      ", dt.minute)
print("Second:      ", dt.second)
print("Microsecond: ", dt.microsecond)

print("\nISO calendar:", dt.isocalendar())
print("Weekday:     ", dt.weekday())
print("ISO format:  ", dt.isoformat())

πŸ“ 3.3 Comparing Datetimes

Datetimes compare naturally β€” earlier is "less than" later.

Step-by-step explanation:

  • Step 1: Create two datetimes.
  • Step 2: Compare with standard operators.
  • Step 3: Subtract to get a timedelta.
python
from datetime import datetime

a = datetime(2026, 1, 1, 9, 0)
b = datetime(2026, 6, 30, 14, 30)

print("a < b:   ", a < b)
print("a == b:  ", a == b)
print("a > b:   ", a > b)

diff = b - a
print("\nDifference:", diff)
print("Days:      ", diff.days)
print("Seconds:   ", diff.seconds)
print("Total secs:", diff.total_seconds())
πŸ’‘ diff.seconds is only the leftover seconds (0–86399). Use total_seconds() for the full duration in seconds.

βž• timedelta β€” Durations & Arithmetic

Represent a span of time and use it to shift dates.

πŸ“ 4.1 Creating a timedelta

Pass days, seconds, microseconds, milliseconds, minutes, hours, or weeks.

Step-by-step explanation:

  • Step 1: Import timedelta.
  • Step 2: Create with keyword arguments.
  • Step 3: Inspect .days and .seconds.
python
from datetime import timedelta

# Common durations
one_day = timedelta(days=1)
one_week = timedelta(weeks=1)
two_hours = timedelta(hours=2)
ninety_mins = timedelta(minutes=90)

print("1 day:      ", one_day)
print("1 week:     ", one_week)
print("2 hours:    ", two_hours)
print("90 minutes: ", ninety_mins)

# Access components
td = timedelta(days=5, hours=3, minutes=45, seconds=30)
print("\nComponents:")
print("  days:   ", td.days)
print("  seconds:", td.seconds)
print("  total_seconds:", td.total_seconds())
πŸ’‘ timedelta stores only days, seconds, and microseconds internally β€” hours and minutes are normalized into those.

πŸ“ 4.2 Datetime Arithmetic

Add or subtract timedelta from any datetime to shift it in time.

Step-by-step explanation:

  • Step 1: Start with a datetime.
  • Step 2: Add or subtract a timedelta.
  • Step 3: Chain multiple operations.
python
from datetime import datetime, timedelta

now = datetime(2026, 6, 30, 12, 0, 0)
print("Now:          ", now)

# Add time
in_2_hours = now + timedelta(hours=2)
print("+2 hours:     ", in_2_hours)

# Subtract time
yesterday = now - timedelta(days=1)
print("-1 day:       ", yesterday)

# Combine offsets
later = now + timedelta(days=7, hours=3, minutes=30)
print("+7d 3h 30m:   ", later)

# Chained
deadline = now + timedelta(weeks=2) - timedelta(days=1)
print("Deadline:     ", deadline)

πŸ“ 4.3 Practical: Age Calculator

Compute age in years, months, and days from a birthdate.

Step-by-step explanation:

  • Step 1: Set the birthdate.
  • Step 2: Compute today's date.
  • Step 3: Calculate days and years elapsed.
python
from datetime import date

birthday = date(1995, 8, 15)
today = date(2026, 6, 30)

age_days = (today - birthday).days
age_years = age_days // 365

print(f"Birthday: {birthday}")
print(f"Today:    {today}")
print(f"Age:      {age_days} days")
print(f"Approx:   {age_years} years")

# Exact age with leap-year correction
years = today.year - birthday.year
if (today.month, today.day) < (birthday.month, birthday.day):
    years -= 1
print(f"Exact:    {years} years")
✨ The exact-year calculation uses tuple comparison β€” neat and readable. No leap-year bugs.

πŸ”€ Formatting & Parsing β€” strftime & strptime

Convert datetimes to strings and back with format codes.

πŸ“ 5.1 strftime() β€” Datetime to String

Format a datetime using format codes like %Y, %m, %d.

Step-by-step explanation:

  • Step 1: Create a datetime.
  • Step 2: Call .strftime(pattern).
  • Step 3: Use popular codes to build readable strings.
python
from datetime import datetime

dt = datetime(2026, 6, 30, 14, 30, 45)

print("ISO:        ", dt.strftime("%Y-%m-%d"))
print("US date:    ", dt.strftime("%m/%d/%Y"))
print("EU date:    ", dt.strftime("%d/%m/%Y"))
print("Long:       ", dt.strftime("%B %d, %Y"))
print("Abbrev:     ", dt.strftime("%b %d, %Y"))
print("Time 24h:   ", dt.strftime("%H:%M:%S"))
print("Time 12h:   ", dt.strftime("%I:%M %p"))
print("Weekday:    ", dt.strftime("%A"))
print("Full:       ", dt.strftime("%A, %B %d, %Y at %I:%M %p"))

πŸ“ 5.2 Common Format Codes

The cheat sheet of strftime / strptime codes you'll actually use.

CodeMeaningExample
%Y4-digit year2026
%y2-digit year26
%mMonth (01–12)06
%dDay (01–31)30
%HHour, 24h (00–23)14
%IHour, 12h (01–12)02
%MMinute (00–59)30
%SSecond (00–59)45
%fMicrosecond123456
%AWeekday (full)Tuesday
%aWeekday (abbr)Tue
%BMonth name (full)June
%bMonth name (abbr)Jun
%pAM/PMPM
%jDay of year181
%zUTC offset+0000
%ZTimezone nameUTC

πŸ“ 5.3 strptime() β€” String to Datetime

Parse a string into a datetime by specifying its format.

Step-by-step explanation:

  • Step 1: Take a string like "2026-06-30 14:30".
  • Step 2: Call datetime.strptime(text, format).
  • Step 3: Handle ValueError for bad input.
python
from datetime import datetime

# Parse a custom format
text = "2026-06-30 14:30:45"
dt = datetime.strptime(text, "%Y-%m-%d %H:%M:%S")
print("Parsed:", dt)
print("Type:  ", type(dt).__name__)

# US date format
us = datetime.strptime("06/30/2026", "%m/%d/%Y")
print("US:    ", us)

# With AM/PM
ampm = datetime.strptime("June 30, 2026 02:30 PM", "%B %d, %Y %I:%M %p")
print("AM/PM: ", ampm)

# Handle parse errors
try:
    datetime.strptime("not a date", "%Y-%m-%d")
except ValueError as e:
    print("\nError:", e)
πŸ’‘ strptime = "string parse time". strftime = "string format time". Same letters, opposite directions β€” a common source of confusion.

🌐 Timezones β€” UTC, Aware & Naive

Handle time zones correctly β€” the source of most datetime bugs.

πŸ“ 6.1 Naive vs Aware Datetimes

A "naive" datetime has no timezone info; an "aware" one does.

Step-by-step explanation:

  • Step 1: A datetime without tzinfo is naive.
  • Step 2: A datetime with tzinfo is aware.
  • Step 3: Never compare naive with aware β€” it raises TypeError.
python
from datetime import datetime, timezone

naive = datetime(2026, 6, 30, 14, 30)
print("Naive:", naive)
print("tzinfo:", naive.tzinfo)

aware = datetime(2026, 6, 30, 14, 30, tzinfo=timezone.utc)
print("\nAware:", aware)
print("tzinfo:", aware.tzinfo)

# Compare safely
try:
    print(naive < aware)
except TypeError as e:
    print("\nError:", e)

# Always compare within the same awareness
print("\nAware vs aware:", aware < datetime(2026, 7, 1, tzinfo=timezone.utc))
⚠️ "Naive vs aware" comparison raises TypeError. This is a feature, not a bug β€” it prevents silent timezone bugs.

πŸ“ 6.2 UTC β€” The Right Default

Store and compute in UTC. Convert to local time only for display.

Step-by-step explanation:

  • Step 1: Get current UTC time with datetime.now(timezone.utc).
  • Step 2: Convert naive β†’ aware with .replace(tzinfo=timezone.utc).
  • Step 3: Convert aware β†’ local with .astimezone().
python
from datetime import datetime, timezone

# Recommended: current UTC time
now_utc = datetime.now(timezone.utc)
print("UTC now:", now_utc)

# Making a naive datetime aware
naive = datetime(2026, 6, 30, 12, 0)
aware = naive.replace(tzinfo=timezone.utc)
print("\nNaive β†’ aware:", aware)

# Convert to local time (works in any timezone)
local = aware.astimezone()
print("Local:        ", local)

# Extract UTC components
print("\nUTC year:  ", aware.year)
print("UTC hour:  ", aware.hour)
print("UTC offset:", aware.utcoffset())
πŸ’‘ The rule of thumb: store UTC, display local. It eliminates a whole class of bugs.

πŸ“ 6.3 Custom Offsets with timezone()

Create fixed-offset timezones like UTC+9 (Tokyo) or UTC-5 (New York standard).

Step-by-step explanation:

  • Step 1: Import timezone and timedelta.
  • Step 2: Create a timezone with timezone(timedelta(hours=9)).
  • Step 3: Attach it to a datetime.
python
from datetime import datetime, timezone, timedelta

tokyo = timezone(timedelta(hours=9))
ny = timezone(timedelta(hours=-5))
utc = timezone.utc

dt = datetime(2026, 6, 30, 15, 0, tzinfo=utc)
print("UTC:   ", dt)
print("Tokyo: ", dt.astimezone(tokyo))
print("NY:    ", dt.astimezone(ny))

# Offsets are accessible
print("\nTokyo offset:", dt.astimezone(tokyo).utcoffset())
print("NY offset:   ", dt.astimezone(ny).utcoffset())
✨ For named zones like "America/New_York" (which handle DST), use Python 3.9+'s zoneinfo module.

❓ Frequently Asked Questions β€” Python Datetime

Common questions about dates and times in Python.

What's the difference between date, time, and datetime?

+

date stores only year, month, day. time stores only hour, minute, second, microsecond. datetime combines both. Use the smallest type you need β€” it makes your intent clearer.

Why is utcnow() deprecated?

+

It returns a naive datetime even though it represents UTC time β€” misleading and error-prone. In Python 3.12+, use datetime.now(timezone.utc) instead. It returns an aware datetime with explicit UTC info.

How do I add months or years to a date?

+

timedelta doesn't support months or years (they vary in length). Use dateutil.relativedelta (from the python-dateutil package) for calendar-aware arithmetic, or compute manually.

What's the difference between strftime and strptime?

+

strftime = "string format time" β€” datetime β†’ string. strptime = "string parse time" β€” string β†’ datetime. Same letters, opposite directions.

How do I compute the difference between two dates in days?

+

Subtract one from the other: (date2 - date1).days. The result is a timedelta, and its .days attribute gives whole days. Use .total_seconds() / 86400 for fractional days.

What's a "naive" vs "aware" datetime?

+

A naive datetime has no tzinfo β€” it's ambiguous. An aware datetime knows its timezone. Python raises TypeError when you compare or subtract them because the result would be wrong.

How do I get the current timestamp as a float?

+

Use datetime.now().timestamp() for local, or datetime.now(timezone.utc).timestamp() for UTC. The result is seconds since the Unix epoch (1970-01-01 00:00 UTC). For milliseconds, multiply by 1000.

How do I handle DST (daylight saving time)?

+

Use zoneinfo (Python 3.9+) with a named zone like "America/New_York". Named zones know their DST rules automatically. Avoid fixed-offset timezone(timedelta(...)) for zones that observe DST.

How do I format a datetime in ISO 8601?

+

Use dt.isoformat() β€” it produces 2026-06-30T14:30:45. For UTC, include the offset: dt.isoformat() on an aware datetime produces 2026-06-30T14:30:45+00:00.

πŸ’› You've Mastered Python Datetime

From basic date, time, and datetime objects to timezone-aware arithmetic and custom formatting, you now have a complete toolkit for handling dates and times in Python. You can compute durations, format for display, parse user input, and reason about timezones correctly.

This curriculum, crafted by @PoeticGlenn, gives you the foundation to work with time in any Python project β€” from logs and analytics to scheduling and user-facing displays. The patterns you've learned will keep your code correct for years.

20 lessons 22+ code examples 1.0k+ learners

"Time is the one resource no debugger can give back. Handle it with care." β€” Glenn Junsay Pansensoy (@PoeticGlenn)