Python Date & Time — datetime Module Mastery

Python Standard LibraryDate and TimeFree Lesson

Advertisement

Python Date & Time — datetime Module Mastery

The datetime module provides classes for manipulating dates, times, and time intervals.

Learning Objectives

  • Create and manipulate date, time, and datetime objects
  • Format dates with strftime and parse with strptime
  • Calculate date differences with timedelta
  • Handle timezones correctly

Creating Dates and Times

from datetime import date, time, datetime, timedelta

# Date object
today = date.today()
print(today)           # 2024-01-15
print(today.year)      # 2024
print(today.month)     # 1
print(today.day)       # 15

specific = date(2024, 12, 25)

# Time object
noon = time(12, 0, 0)
print(noon.hour)       # 12

# Datetime object
now = datetime.now()
specific_dt = datetime(2024, 6, 15, 14, 30, 0)

Formatting Dates

now = datetime.now()

# strftime — format datetime to string
print(now.strftime("%Y-%m-%d"))           # 2024-01-15
print(now.strftime("%B %d, %Y"))          # January 15, 2024
print(now.strftime("%I:%M %p"))           # 02:30 PM
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # 2024-01-15 14:30:00

# Common format codes
# %Y — Year (4 digits)    %m — Month (01-12)
# %d — Day (01-31)        %H — Hour (00-23)
# %M — Minute (00-59)     %S — Second (00-59)
# %B — Full month name    %b — Abbreviated month
# %A — Full weekday name  %p — AM/PM

Parsing Dates

# strptime — parse string to datetime
date_str = "2024-06-15"
dt = datetime.strptime(date_str, "%Y-%m-%d")

# Flexible parsing
dt = datetime.strptime("15/06/2024 14:30", "%d/%m/%Y %H:%M")
dt = datetime.strptime("June 15, 2024", "%B %d, %Y")

timedelta — Date Arithmetic

from datetime import timedelta

today = date.today()

# Add/subtract days
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
next_month = today + timedelta(days=30)

# Date difference
birthday = date(1990, 5, 15)
age = today - birthday
print(f"You are {age.days} days old")

# Time difference
start = datetime.now()
import time
time.sleep(2)
elapsed = datetime.now() - start
print(f"Elapsed: {elapsed.total_seconds():.1f} seconds")

Timezones

from datetime import timezone, timedelta

# UTC
utc_now = datetime.now(timezone.utc)

# Specific timezone
est = timezone(timedelta(hours=-5))
eastern_now = datetime.now(est)

# Convert between timezones (Python 3.9+)
from zoneinfo import ZoneInfo
tokyo_tz = ZoneInfo("Asia/Tokyo")
tokyo_now = datetime.now(tokyo_tz)

Key Takeaways

  1. date for calendar dates, time for times, datetime for both
  2. strftime() formats to string, strptime() parses from string
  3. timedelta handles date arithmetic
  4. Always use timezone.utc for timezone-aware datetimes
  5. Use zoneinfo (Python 3.9+) for timezone support

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement