Cyber Services / All lessons / Python Programming / Working with Date and Time

Working with Date and Time

Module 23 of 31 · 4 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Mastering Time, Timestamps, Formatting, and Timezones in Python

Why Date/Time Handling Matters

From logging events and scheduling tasks to analyzing time-series data and building user interfaces, working with dates and times is essential in almost every real-world application. Python provides powerful built-in modules to handle these tasks accurately and efficiently.

Core Modules: datetime, time, and calendar

  • datetime: Most comprehensive—handles dates, times, timezones, and arithmetic.
  • time: Low-level—Unix timestamps, sleep, performance timing.
  • calendar: Utilities for calendars, leap years, month layouts.

The datetime Module: Core Classes

Class Purpose
dateYear, month, day (no time)
timeHour, minute, second, microsecond (no date)
datetimeCombines date + time (most commonly used)
timedeltaRepresents duration (difference between two dates/times)
timezoneRepresents timezone info (UTC, EST, etc.)

Getting Current Date and Time

Current Local and UTC Time
from datetime import datetime, timezone

# Current local date and time
now_local = datetime.now()
print("Local:", now_local)  
# e.g., 2024-06-15 14:30:45.123456

# Current UTC time
now_utc = datetime.now(timezone.utc)
print("UTC:", now_utc)
# e.g., 2024-06-15 10:30:45.123456+00:00

Creating Custom Date/Time Objects

Constructing datetime Objects
from datetime import datetime, date, time

# Full datetime
dt = datetime(2025, 12, 25, 18, 30, 0)
print(dt)  # 2025-12-25 18:30:00

# Date only
d = date(2025, 12, 25)
print(d)  # 2025-12-25

# Time only
t = time(18, 30, 0)
print(t)  # 18:30:00

Formatting and Parsing: strftime() and strptime()

Convert between datetime objects and human-readable strings.

Directive Meaning Example
%Y4-digit year2024
%mMonth (01–12)06
%dDay (01–31)15
%HHour (00–23)14
%MMinute (00–59)30
%SSecond (00–59)45
%AFull weekdaySaturday
%BFull monthJune
Formatting and Parsing Examples
from datetime import datetime

now = datetime.now()

# Format to string
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 2024-06-15 14:30:45

# Human-readable
readable = now.strftime("%A, %B %d, %Y at %I:%M %p")
print(readable)  # Saturday, June 15, 2024 at 02:30 PM

# Parse string to datetime
date_str = "2024-12-25 18:30:00"
parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed)  # 2024-12-25 18:30:00

Date and Time Arithmetic with timedelta

Perform calculations like "add 7 days" or "find difference between two dates."

Time Calculations
from datetime import datetime, timedelta

now = datetime.now()

# Add time
future = now + timedelta(days=7, hours=3)
print("Next week:", future)

# Subtract time
past = now - timedelta(weeks=2)
print("Two weeks ago:", past)

# Difference between dates
birthday = datetime(2025, 1, 1)
days_until = (birthday - now).days
print(f"Days until New Year: {days_until}")

# Total seconds
duration = timedelta(hours=2, minutes=30)
print(duration.total_seconds())  # 9000.0

Working with Timezones

Use timezone.utc for UTC, or third-party libraries like pytz or zoneinfo (Python 3.9+) for other timezones.

Timezone-Aware Datetimes
from datetime import datetime, timezone, timedelta

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

# Create EST timezone (UTC-5)
est = timezone(timedelta(hours=-5))
est_time = utc_now.astimezone(est)

print("UTC:", utc_now.isoformat())
print("EST:", est_time.isoformat())

# Convert between timezones
print("Back to UTC:", est_time.astimezone(timezone.utc))

The time Module: Low-Level Operations

Unix Timestamps and Performance Timing
import time

# Current time as Unix timestamp (seconds since 1970-01-01 UTC)
timestamp = time.time()
print("Timestamp:", timestamp)  # e.g., 1718456445.123

# Convert to readable string
readable = time.ctime(timestamp)
print("Readable:", readable)  # Sat Jun 15 14:30:45 2024

# Sleep for 2 seconds
print("Waiting...")
time.sleep(2)
print("Done!")

# Measure execution time
start = time.perf_counter()
# ... some code ...
end = time.perf_counter()
print(f"Execution time: {end - start:.4f} seconds")

The calendar Module

Calendar Utilities
import calendar

# Check leap year
print(calendar.isleap(2024))  # True

# Days in month
print(calendar.monthrange(2024, 2))  # (3, 29) → Feb 2024 has 29 days, starts on Thursday (3)

# Print calendar
print(calendar.month(2024, 6))
#      June 2024
# Mo Tu We Th Fr Sa Su
#                 1  2
#  3  4  5  6  7  8  9
# 10 11 12 13 14 15 16
# 17 18 19 20 21 22 23
# 24 25 26 27 28 29 30

Best Practices

  • ✅ Always use timezone-aware datetimes in production systems.
  • ✅ Store datetimes in UTC in databases; convert to local time only for display.
  • ✅ Use datetime.now(timezone.utc) instead of naive datetime.now() for accuracy.
  • ✅ Prefer ISO 8601 format (%Y-%m-%dT%H:%M:%S) for data interchange.
  • ✅ Use time.perf_counter() for benchmarking, not time.time().

Common Pitfalls

  • ❌ Using naive datetimes (no timezone) in distributed systems → bugs during DST changes.
  • ❌ Assuming datetime.now() is UTC—it’s local time!
  • ❌ Parsing ambiguous date strings (e.g., "01/02/03") without specifying format.
  • ❌ Ignoring leap seconds and daylight saving time edge cases.

Key Takeaways

  • The datetime module is your primary tool for date/time work.
  • Use strftime() and strptime() for formatting and parsing.
  • timedelta enables powerful date arithmetic.
  • Always handle timezones explicitly to avoid subtle bugs.
  • For complex timezone handling, consider zoneinfo (Python 3.9+) or pytz.
Modules (31) ← Python Programming