Working with dates and times is a common requirement—from logging events to scheduling tasks. Python’s standard library offers powerful tools in the datetime, time, and zoneinfo modules, letting you represent, format, parse, and compute with temporal data. In this chapter, you’ll learn how to:
- Get the current date and time
- Create and inspect
date,time, anddatetimeobjects - Format and parse dates with
strftime()andstrptime() - Perform date/time arithmetic with
timedelta - Handle time zones and “aware” datetimes
- Build a mini age-calculator project
1. Getting Started: Importing Modules
Before diving in, import the key classes and functions:
from datetime import date, time, datetime, timedelta, timezone
import time as time_module # for low-level time functions
from zoneinfo import ZoneInfo # Python 3.9+ for IANA time zones
datetimemodule: High-level date/time types and arithmetic.timemodule: Lower-level functions (sleep, timestamps).zoneinfo(3.9+): Standard time zone database support.
2. The date Class: Dates Only
A date object holds a year, month, and day:
# Today’s date
today = date.today()
print(today) # e.g., 2025-06-29
print(today.year) # 2025
print(today.month) # 6
print(today.day) # 29
# Creating a specific date
independence = date(1947, 8, 14)
print(independence) # 1947-08-14
Use date when you care about calendar days, without clock times.
3. The time Class: Clock Times Only
A time object represents hours, minutes, seconds, and microseconds:
# Create a time object
lunchtime = time(12, 30, 0)
print(lunchtime) # 12:30:00
# Access attributes
print(lunchtime.hour) # 12
print(lunchtime.minute) # 30
print(lunchtime.second) # 0
Combine date and time into a datetime when both matter.
4. The datetime Class: Dates & Times Together
datetime merges date and time, plus utility methods:
# Current local datetime
now = datetime.now()
print(now) # 2025-06-29 13:45:02.123456
# UTC datetime
utc_now = datetime.utcnow()
print(utc_now) # 2025-06-29 08:45:02.123456
# From timestamp (seconds since epoch)
dt_from_ts = datetime.fromtimestamp(time_module.time())
print(dt_from_ts)
# Building a specific datetime
meeting = datetime(2025, 7, 10, 15, 0, 0)
print(meeting) # 2025-07-10 15:00:00
- Use
now()for local time,utcnow()for naïve UTC. - To create “aware” datetimes, attach a
tzinfo.
5. Formatting with strftime()
Turn dates/times into strings using format codes:
fmt = "%Y-%m-%d %H:%M:%S"
print(now.strftime(fmt)) # "2025-06-29 13:45:02"
# Common directives:
# %Y Year with century (2025)
# %m Month as 01-12
# %d Day of month 01-31
# %H Hour (00-23)
# %M Minute 00-59
# %S Second 00-59
# %A Weekday name ("Sunday")
A concise reference of directives helps you build any custom format.
6. Parsing with strptime()
Convert a string back into a datetime by matching the format:
s = "2025-06-29 13:45:02"
parsed = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
print(parsed) # datetime(2025, 6, 29, 13, 45, 2)
Use the same directives as strftime() to ensure accurate parsing.
7. Date & Time Arithmetic with timedelta
Compute intervals by adding or subtracting timedelta objects:
# One week from today
one_week = timedelta(weeks=1)
print(today + one_week) # e.g., 2025-07-06
# Subtract 2 hours from now
two_hours = timedelta(hours=2)
print(now - two_hours) # 2025-06-29 11:45:02.123456
# Difference between two datetimes
delta = meeting - now
print(delta.days, delta.seconds)
timedelta supports days, seconds, microseconds, milliseconds, minutes, hours, and weeks.
8. Time Zones: Naïve vs. Aware
By default, datetime objects are naïve—they lack time zone info. To work safely across zones, create aware datetimes:
# Aware UTC time
aware_utc = datetime.now(timezone.utc)
print(aware_utc.tzinfo) # UTC
# Localize with IANA zone
ny_tz = ZoneInfo("America/New_York")
ny_time = datetime.now(ny_tz)
print(ny_time) # 2025-06-29 09:45:02-04:00
# Convert between zones
tokyo_tz = ZoneInfo("Asia/Tokyo")
tokyo_time = ny_time.astimezone(tokyo_tz)
print(tokyo_time) # 2025-06-29 22:45:02+09:00
- Always use aware datetimes in distributed apps to avoid ambiguity.
- The standard library’s
zoneinfotaps the IANA database.
9. Mini Project: Age Calculator
Create a script that asks for a birth date, computes the exact age in years, months, and days, and handles time zones.
from datetime import date
def calculate_age(birth: date, today: date) -> tuple[int,int,int]:
"""Return (years, months, days) between birth and today."""
# Start with whole years
years = today.year - birth.year
# Adjust if birthday hasn’t occurred yet this year
if (today.month, today.day) < (birth.month, birth.day):
years -= 1
# Compute remaining months and days
month_diff = today.month - birth.month
day_diff = today.day - birth.day
if day_diff < 0:
# borrow days from previous month
from calendar import monthrange
prev_month = (today.month - 1) or 12
prev_year = today.year if today.month != 1 else today.year - 1
days_in_prev = monthrange(prev_year, prev_month)[1]
day_diff += days_in_prev
month_diff -= 1
if month_diff < 0:
month_diff += 12
return years, month_diff, day_diff
if __name__ == "__main__":
b_str = input("Enter your birth date (YYYY-MM-DD): ")
birth = date.fromisoformat(b_str)
today = date.today()
y, m, d = calculate_age(birth, today)
print(f"You are {y} years, {m} months, and {d} days old.")
How It Works:
- Parse the ISO date string with
date.fromisoformat(). - Compute year difference, adjusting if birthday hasn’t passed.
- Calculate remaining months and days, borrowing days when needed.
10. Conclusion
Python’s date and time tools—spanning date, time, datetime, timedelta, and time zone support—equip you to represent, format, parse, and compute temporal data accurately. From simple timestamps to cross-zone conversions and custom age calculations, mastering these classes is key to building robust, time-aware applications. Happy coding!
Discover more from Affordable Tutor
Subscribe to get the latest posts sent to your email.


