pyguides

datetime

The datetime module provides classes for manipulating dates and times. It is one of the most frequently used standard library modules for any application that deals with time-related data.

datetime.datetime

The datetime class combines a date and a time into a single object.

Constructors

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
datetime.now(tz=None)           # Current local datetime
datetime.today()                # Current local datetime (no tzinfo)
datetime.utcnow()               # Current UTC datetime (deprecated)
datetime.fromtimestamp(timestamp, tz=None)     # From Unix timestamp
datetime.strptime(date_string, format)        # Parse from string

Attributes

AttributeTypeRange
yearint1-9999
monthint1-12
dayint1-31
hourint0-23
minuteint0-59
secondint0-59
microsecondint0-999999
tzinfotzinfo or None-

Methods

datetime.date()              # Return date part
datetime.time()              # Return time part
datetime.timetz()            # Return time part with tzinfo
datetime.replace(...)        # Return new datetime with changes
datetime.strftime(format)    # Format as string
datetime.timestamp()         # Return Unix timestamp
datetime.weekday()          # Return day of week (0=Monday)
datetime.isoweekday()       # Return day of week (1=Monday)
datetime.isocalendar()      # Return (ISO year, ISO week, ISO day)

Examples

from datetime import datetime, timezone

# Current datetime
now = datetime.now()
print(now)
# 2026-03-08 20:27:45.123456

# Specific datetime
dt = datetime(2026, 3, 8, 14, 30, 0)
print(dt)
# 2026-03-08 14:30:00

# Parse from string
parsed = datetime.strptime("2026-03-08 14:30:00", "%Y-%m-%d %H:%M:%S")
print(parsed)
# 2026-03-08 14:30:00

# Format datetime
formatted = now.strftime("%B %d, %Y at %I:%M %p")
print(formatted)
# March 08, 2026 at 08:27 PM

# With timezone
aware = datetime.now(timezone.utc)
print(aware)
# 2026-03-08 20:27:45.123456+00:00

datetime.date

The date class represents a date (year, month, day) without a time component.

Constructors

date(year, month, day)
date.today()           # Current date
date.fromtimestamp(timestamp)   # From Unix timestamp
date.fromordinal(ordinal)       # From proleptic Gregorian ordinal

Methods

date.replace(...)       # Return new date
date.strftime(format)   # Format as string
date.weekday()         # 0=Monday
date.isoweekday()      # 1=Monday
date.isocalendar()     # (ISO year, ISO week, ISO day)
date.toordinal()       # Proleptic Gregorian ordinal

Examples

from datetime import date

today = date.today()
print(today)
# 2026-03-08

specific = date(2026, 12, 25)
print(specific)
# 2026-12-25

# Date arithmetic
new_year = date(2027, 1, 1)
days_until = (new_year - today).days
print(f"Days until New Year: {days_until}")
# Days until New Year: 299

datetime.time

The time class represents a time of day independent of any particular date.

Constructors

time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

Attributes

AttributeTypeRange
hourint0-23
minuteint0-59
secondint0-59
microsecondint0-999999
tzinfotzinfo or None-

Examples

from datetime import time

t = time(14, 30, 45)
print(t)
# 14:30:45

# Format
print(t.strftime("%I:%M %p"))
# 02:30 PM

datetime.timedelta

The timedelta class represents a duration - the difference between two dates or times.

Constructors

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Attributes

AttributeType
daysint
secondsint
microsecondsint

Properties

td.total_seconds()    # Total seconds as float

Examples

from datetime import datetime, timedelta, date

# Date arithmetic
now = datetime.now()
one_week_later = now + timedelta(weeks=1)
print(one_week_later)
# 2026-03-15 20:27:45.123456

# Duration between dates
dt1 = datetime(2026, 1, 1)
dt2 = datetime(2026, 3, 8)
delta = dt2 - dt1
print(delta.days)
# 66
print(delta.total_seconds())
# 5702400.0

# Calculate business days
def business_days(start, end):
    delta = end - start
    business = sum(1 for i in range(delta.days) 
                  if (start + timedelta(days=i)).weekday() < 5)
    return business

print(business_days(date(2026, 1, 1), date(2026, 1, 31)))
# 22

datetime.timezone

The timezone class represents a fixed offset from UTC.

Constructors

timezone(offset, name=None)    # offset is a timedelta
timezone.utc                   # UTC timezone

Examples

from datetime import datetime, timezone, timedelta

# Fixed offset
eastern = timezone(timedelta(hours=-5), "EST")
dt = datetime(2026, 3, 8, 14, 30, 0, tzinfo=eastern)
print(dt)
# 2026-03-08 14:30:00-05:00

# UTC
utc_dt = datetime.now(timezone.utc)
print(utc_dt)
# 2026-03-08 20:27:45.123456+00:00

# Convert between timezones
est = timezone(timedelta(hours=-5))
pst = timezone(timedelta(hours=-8))

dt_est = datetime(2026, 3, 8, 14, 30, tzinfo=est)
dt_pst = dt_est.astimezone(pst)
print(dt_pst)
# 2026-03-08 11:30:00-08:00

Common Patterns

Age calculation

from datetime import date

def age(birthday):
    today = date.today()
    age = today.year - birthday.year
    if (today.month, today.day) < (birthday.month, birthday.day):
        age -= 1
    return age

print(age(date(1990, 6, 15)))
# 35

Unix timestamp conversion

from datetime import datetime, timezone

# datetime to timestamp
dt = datetime(2026, 3, 8, 14, 30, 0, tzinfo=timezone.utc)
print(dt.timestamp())
# 1772980200.0

# timestamp to datetime
ts = 1772980200.0
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print(dt)
# 2026-03-08 14:30:00+00:00

See Also