Skip to content

Dates and Times

Work with dates and times using datetime, timedelta, formatting, timezones, and parsing.

What you'll learn

  • Create date, time, and datetime objects
  • Perform arithmetic with timedelta
  • Format and parse dates with strftime and strptime
  • Handle timezones with zoneinfo
  • Calculate durations and compare dates

Concept

The datetime Module

The datetime module is Python's standard library for date and time manipulation. It provides four main types:

  • date — year, month, day (no time)
  • time — hour, minute, second, microsecond (no date)
  • datetime — both date and time
  • timedelta — a duration (difference between two datetimes)
from datetime import date, time, datetime, timedelta

today = date.today()               # 2024-01-15
now = datetime.now()               # 2024-01-15 14:30:45.123456
specific = date(2024, 7, 4)        # July 4, 2024
moment = datetime(2024, 7, 4, 12, 0, 0)  # July 4, 2024 at noon

Creating Date and Time Objects

from datetime import date, time, datetime

# date — just a calendar date
d = date(2024, 1, 15)
print(d.year, d.month, d.day)  # 2024 1 15

# time — just a clock time (no date)
t = time(14, 30, 45)
print(t.hour, t.minute, t.second)  # 14 30 45

# datetime — both date and time
dt = datetime(2024, 1, 15, 14, 30, 45)
print(dt)  # 2024-01-15 14:30:45

# From a timestamp (Unix epoch)
from_timestamp = datetime.fromtimestamp(1705312200)

Formatting and Parsing

Use strftime() (string format time) to convert to a string, and strptime() (string parse time) to parse from a string:

from datetime import datetime

dt = datetime(2024, 1, 15, 14, 30, 45)

# Format to string
print(dt.strftime("%Y-%m-%d"))        # 2024-01-15
print(dt.strftime("%B %d, %Y"))       # January 15, 2024
print(dt.strftime("%H:%M:%S"))        # 14:30:45
print(dt.strftime("%Y-%m-%d %H:%M"))  # 2024-01-15 14:30

# Parse from string
parsed = datetime.strptime("2024-01-15", "%Y-%m-%d")
print(parsed)  # 2024-01-15 00:00:00

Common format codes: | Code | Meaning | Example | |------|---------|---------| | %Y | 4-digit year | 2024 | | %m | 2-digit month | 01 | | %d | 2-digit day | 15 | | %H | hour (24h) | 14 | | %M | minute | 30 | | %S | second | 45 | | %B | full month name | January | | %b | abbreviated month | Jan | | %A | full weekday | Monday | | %I | hour (12h) | 02 | | %p | AM/PM | PM |

timedelta — Date Arithmetic

timedelta represents a duration. You can add and subtract it from dates:

from datetime import date, timedelta

today = date.today()
one_week = timedelta(weeks=1)
yesterday = today - timedelta(days=1)
next_week = today + one_week

# Differences between dates produce timedelta
diff = date(2024, 12, 31) - date(2024, 1, 1)
print(diff.days)  # 365

# timedelta components
td = timedelta(days=2, hours=6, minutes=30)
print(td.total_seconds())  # 198000.0
from datetime import datetime, timedelta

now = datetime.now()
future = now + timedelta(days=30, hours=12)
past = now - timedelta(weeks=2)

print(f"Now: {now}")
print(f"30 days 12 hours later: {future}")
print(f"2 weeks ago: {past}")

# Difference between two datetimes
duration = future - now
print(f"Duration: {duration}")  # 30 days, 12:00:00
print(f"Total seconds: {duration.total_seconds()}")

Comparing Dates

Dates and datetimes support comparison operators:

from datetime import date

d1 = date(2024, 1, 15)
d2 = date(2024, 7, 4)

print(d1 < d2)   # True
print(d1 == d1)  # True
print(max(d1, d2))  # 2024-07-04

# Check if a date is in a range
start = date(2024, 1, 1)
end = date(2024, 12, 31)
print(start <= d1 <= end)  # True

Timezones

Python 3.9+ includes zoneinfo for timezone support:

from datetime import datetime
from zoneinfo import ZoneInfo

# Create timezone-aware datetimes
utc_now = datetime.now(ZoneInfo("UTC"))
tokyo_now = datetime.now(ZoneInfo("Asia/Tokyo"))
ny_now = datetime.now(ZoneInfo("America/New_York"))

print(f"UTC: {utc_now}")
print(f"Tokyo: {tokyo_now}")
print(f"New York: {ny_now}")

# Convert between timezones
tokyo_time = utc_now.astimezone(ZoneInfo("Asia/Tokyo"))

Always use timezone-aware datetimes in applications — naive datetimes (without timezone info) are a common source of bugs. Use datetime.now(ZoneInfo("UTC")) instead of datetime.now().

Practical Examples

from datetime import datetime, timedelta

# Age calculation
def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year
    # Adjust if birthday hasn't occurred this year
    if (today.month, today.day) < (birth_date.month, birth_date.day):
        age -= 1
    return age

# Days until a target date
def days_until(target):
    return (target - date.today()).days

Example

              from datetime import date, time, datetime, timedelta

# Creating objects
today = date.today()
now = datetime.now()
specific = datetime(2024, 7, 4, 12, 0, 0)
print(f"Today: {today}")
print(f"Now: {now}")
print(f"Specific: {specific}")

# Formatting
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%B %d, %Y at %I:%M %p"))

# Parsing
parsed = datetime.strptime("2024-12-25", "%Y-%m-%d")
print(f"Parsed Christmas: {parsed}")

# timedelta arithmetic
one_week_later = today + timedelta(weeks=1)
yesterday = today - timedelta(days=1)
print(f"One week later: {one_week_later}")
print(f"Yesterday: {yesterday}")

# Difference between dates
diff = date(2024, 12, 31) - date(2024, 1, 1)
print(f"Days in 2024: {diff.days}")

# Comparing dates
d1, d2 = date(2024, 1, 15), date(2024, 7, 4)
print(f"d1 < d2: {d1 < d2}")
print(f"Max: {max(d1, d2)}")

# Age calculation
def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year
    if (today.month, today.day) < (birth_date.month, birth_date.day):
        age -= 1
    return age

ada_birthday = date(1815, 12, 10)
print(f"Ada Lovelace would be: {calculate_age(ada_birthday)}")

# Timezone (Python 3.9+)
from zoneinfo import ZoneInfo
utc = datetime.now(ZoneInfo("UTC"))
tokyo = utc.astimezone(ZoneInfo("Asia/Tokyo"))
print(f"UTC: {utc.strftime('%H:%M')}")
print(f"Tokyo: {tokyo.strftime('%H:%M')}")
            

Shows creating date/datetime objects, formatting with strftime, parsing with strptime, timedelta arithmetic, date comparison, an age calculation function, and timezone conversion between UTC and Tokyo.

Try it

  • JSON Formatter

    Dates are often serialized to JSON — ISO format strings are standard.

  • Text Counter

    Timestamps in logs are parsed and analyzed with datetime.

Common mistakes

The mistake

Using naive datetimes (without timezone) and getting wrong results across timezones

The fix

Always use timezone-aware datetimes: datetime.now(ZoneInfo('UTC')) instead of datetime.now(). Naive datetimes silently produce wrong results when compared or converted across timezones. Use zoneinfo (Python 3.9+) for timezone support.

The mistake

Confusing strftime (format to string) with strptime (parse from string)

The fix

strftime = string FROM time (datetime → string). strptime = string PARSE time (string → datetime). The 'f' in strftime stands for 'format', the 'p' in strptime stands for 'parse'. Remember: strftime outputs, strptime inputs.

Related Cheatsheets

Practice Dates and Times

1 exercise

Practice Dates and Times

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors