Python Lesson 28 – Date & Time | Dataplexa

Date & Time

Dates and times appear in almost every real application — order timestamps, user activity logs, scheduled tasks, billing cycles, and data exports all depend on accurate time handling. Python's built-in datetime module gives you everything you need to create, format, parse, compare, and do arithmetic with dates and times without any third-party packages.

This lesson covers the four core classes in the module, formatting and parsing, timedelta arithmetic, timezones, and the practical patterns you will use constantly in production code.

The Four Core Classes

The datetime module provides four main classes. Each has a distinct role and knowing which to reach for saves a lot of confusion.

  • date — stores a calendar date: year, month, day only
  • time — stores a time of day: hour, minute, second, microsecond only
  • datetime — stores both date and time combined — the most commonly used class
  • timedelta — represents a duration or difference between two points in time
# Importing the four core classes

from datetime import date, time, datetime, timedelta

# date — year, month, day
d = date(2024, 7, 19)
print(d)              # 2024-07-19
print(d.year)         # 2024
print(d.month)        # 7
print(d.day)          # 19

# time — hour, minute, second, microsecond
t = time(14, 30, 0)
print(t)              # 14:30:00

# datetime — date AND time combined
dt = datetime(2024, 7, 19, 14, 30, 0)
print(dt)             # 2024-07-19 14:30:00

# timedelta — a duration
delta = timedelta(days=7, hours=3)
print(delta)          # 7 days, 3:00:00
2024-07-19
2024
7
19
14:30:00
2024-07-19 14:30:00
7 days, 3:00:00
  • Import from datetime — the module and the class share the same name, so from datetime import datetime is the standard pattern
  • Month and day are 1-indexed — January is 1, not 0
  • Hours use 24-hour format — 14 is 2:00 PM

Getting the Current Date and Time

The most common starting point in any time-related task is getting right now. Python provides dedicated class methods for this.

# Getting the current date and time

from datetime import date, datetime

today = date.today()
print("Today:", today)

now = datetime.now()
print("Now:", now)

# Access individual components
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)

# Day of the week — Monday=0, Sunday=6
print("Weekday:", now.weekday())
print("Day name:", now.strftime("%A"))   # covered in next section
Today: 2024-07-19
Now: 2024-07-19 14:32:05.123456
Year: 2024
Month: 7
Day: 19
Hour: 14
Minute: 32
Second: 5
Weekday: 4
Day name: Friday
  • date.today() returns today's date with no time component
  • datetime.now() returns the current local date and time including microseconds
  • datetime.utcnow() returns the current UTC time — preferred for storing timestamps in databases
  • weekday() returns 0 for Monday through 6 for Sunday

Formatting Dates — strftime()

strftime() converts a date or datetime object into a formatted string. The name stands for "string format time". You control the output using format codes that start with %.

Why it exists: different countries, systems, and users expect dates in different formats. strftime() lets you produce exactly the format required — US style, European style, ISO 8601, or anything custom.

Real-world use: generating a filename that includes the current date, formatting a timestamp for a receipt, or displaying a human-readable date in a web app.

# strftime() — format a datetime as a string

from datetime import datetime

dt = datetime(2024, 7, 19, 14, 30, 5)

# Common format patterns
print(dt.strftime("%Y-%m-%d"))           # 2024-07-19  (ISO 8601)
print(dt.strftime("%m/%d/%Y"))           # 07/19/2024  (US style)
print(dt.strftime("%d-%b-%Y"))           # 19-Jul-2024
print(dt.strftime("%B %d, %Y"))          # July 19, 2024
print(dt.strftime("%I:%M %p"))           # 02:30 PM    (12-hour clock)
print(dt.strftime("%H:%M:%S"))           # 14:30:05    (24-hour clock)
print(dt.strftime("%A, %B %d, %Y"))      # Friday, July 19, 2024

# Use in a filename
filename = dt.strftime("report_%Y%m%d_%H%M%S.csv")
print(filename)                          # report_20240719_143005.csv
2024-07-19
07/19/2024
19-Jul-2024
July 19, 2024
02:30 PM
14:30:05
Friday, July 19, 2024
report_20240719_143005.csv
  • %Y four-digit year, %m zero-padded month, %d zero-padded day
  • %H 24-hour hour, %I 12-hour hour, %M minutes, %S seconds
  • %A full weekday name, %B full month name, %b abbreviated month name
  • %p AM/PM indicator

Parsing Strings into Dates — strptime()

strptime() does the reverse of strftime() — it parses a date string and converts it into a datetime object. The name stands for "string parse time".

Real-world use: a CSV file contains dates as strings like "19/07/2024" — you parse them with strptime() so you can sort, compare, and do arithmetic with them.

# strptime() — parse a date string into a datetime object

from datetime import datetime

# The format string must match the input string exactly
dt1 = datetime.strptime("2024-07-19", "%Y-%m-%d")
print(dt1)          # 2024-07-19 00:00:00

dt2 = datetime.strptime("07/19/2024 02:30 PM", "%m/%d/%Y %I:%M %p")
print(dt2)          # 2024-07-19 14:30:00

dt3 = datetime.strptime("19-Jul-2024", "%d-%b-%Y")
print(dt3)          # 2024-07-19 00:00:00

# Now you can compare, sort, or do arithmetic
dates = ["2024-03-15", "2024-01-02", "2024-06-30"]
parsed = [datetime.strptime(d, "%Y-%m-%d") for d in dates]
print(sorted(parsed))
2024-07-19 00:00:00
2024-07-19 14:30:00
2024-07-19 00:00:00
[datetime.datetime(2024, 1, 2, 0, 0), datetime.datetime(2024, 3, 15, 0, 0), datetime.datetime(2024, 6, 30, 0, 0)]
  • strptime(string, format) is a class method — call it on datetime, not on an instance
  • The format string must exactly match the structure of the input string
  • Raises ValueError if the string does not match the format
  • Once parsed, use .date() or .time() to extract just the date or time part

Date Arithmetic with timedelta

A timedelta represents a span of time. You can add or subtract timedeltas from dates and datetimes to calculate future or past moments, and subtract two dates to find the gap between them.

Real-world use: calculating a subscription renewal date (30 days from signup), finding how many days since a user last logged in, or checking whether a coupon has expired.

# timedelta arithmetic — adding and subtracting time

from datetime import date, datetime, timedelta

today = date(2024, 7, 19)

# Add days
next_week    = today + timedelta(days=7)
in_30_days   = today + timedelta(days=30)
print("Next week:", next_week)
print("In 30 days:", in_30_days)

# Subtract days
last_week    = today - timedelta(days=7)
print("Last week:", last_week)

# Difference between two dates — result is a timedelta
start = date(2024, 1, 1)
end   = date(2024, 7, 19)
gap   = end - start
print("Days elapsed:", gap.days)

# timedelta with hours and minutes
deadline = datetime(2024, 7, 19, 9, 0, 0)
extended = deadline + timedelta(hours=2, minutes=30)
print("Extended deadline:", extended)
Next week: 2024-07-26
In 30 days: 2024-08-18
Last week: 2024-07-12
Days elapsed: 200
Extended deadline: 2024-07-19 11:30:00
  • timedelta accepts: days, seconds, microseconds, milliseconds, minutes, hours, weeks
  • Subtracting two date or datetime objects always returns a timedelta
  • Access the result with .days, .seconds, or .total_seconds()
  • .total_seconds() is the safest way to get the full duration as a single number

Comparing Dates and Datetimes

Date and datetime objects support all standard comparison operators — <, >, ==, !=, <=, >=. This makes sorting, filtering, and deadline checking straightforward.

# Comparing dates and datetimes

from datetime import date, datetime

d1 = date(2024, 1, 1)
d2 = date(2024, 7, 19)

print(d1 < d2)    # True  — d1 is earlier
print(d1 == d2)   # False
print(d2 > d1)    # True

# Check if a date is in the past or future
today = date.today()
expiry = date(2025, 12, 31)

if expiry > today:
    print("Not yet expired")
else:
    print("Expired")
True
False
True
Not yet expired
  • You can only compare objects of the same type — comparing a date to a datetime raises a TypeError
  • Use datetime.combine(date, time) to merge a date and time into a datetime for comparison

Working with Timezones

A naive datetime has no timezone information. An aware datetime knows its timezone. For any application that handles users in multiple locations or stores timestamps in a database, you should use aware datetimes.

Real-world use: a global e-commerce platform stores all order timestamps in UTC, then converts to the customer's local timezone only when displaying them.

# Timezones using Python's built-in zoneinfo module (Python 3.9+)

from datetime import datetime
from zoneinfo import ZoneInfo

# Create a timezone-aware datetime in UTC
utc_now = datetime.now(tz=ZoneInfo("UTC"))
print("UTC:", utc_now.strftime("%Y-%m-%d %H:%M %Z"))

# Convert to US Eastern time
eastern = utc_now.astimezone(ZoneInfo("America/New_York"))
print("Eastern:", eastern.strftime("%Y-%m-%d %H:%M %Z"))

# Convert to US Pacific time
pacific = utc_now.astimezone(ZoneInfo("America/Los_Angeles"))
print("Pacific:", pacific.strftime("%Y-%m-%d %H:%M %Z"))
UTC: 2024-07-19 14:30 UTC
Eastern: 2024-07-19 10:30 EDT
Pacific: 2024-07-19 07:30 PDT
  • zoneinfo is built into Python 3.9+ — no third-party package needed for basic timezone work
  • Pass tz=ZoneInfo("UTC") to datetime.now() to get an aware datetime
  • .astimezone(tz) converts an aware datetime to a different timezone
  • For Python 3.8 and below, use the pytz library for the same functionality

Summary Table

Tool Purpose Key Method / Usage
date Calendar date only date.today()
datetime Date and time combined datetime.now()
timedelta Duration / date arithmetic timedelta(days=n)
strftime() datetime → formatted string dt.strftime("%Y-%m-%d")
strptime() String → datetime object datetime.strptime(s, fmt)
ZoneInfo Timezone-aware datetimes datetime.now(tz=ZoneInfo("UTC"))

Practice Questions

Practice 1. Which class would you use to store only a calendar date with no time component?



Practice 2. What method converts a datetime object into a formatted string?



Practice 3. What type is returned when you subtract two date objects from each other?



Practice 4. What format code produces a four-digit year in strftime()?



Practice 5. What is the difference between a naive and an aware datetime?



Quiz

Quiz 1. What does date.today() return?






Quiz 2. What does datetime.strptime("2024-07-19", "%Y-%m-%d") return?






Quiz 3. Which timedelta attribute gives you the total duration as a single float in seconds?






Quiz 4. What integer does weekday() return for Monday?






Quiz 5. Which module built into Python 3.9+ handles timezone-aware datetimes?






Next up — Virtual Environments: isolating project dependencies so your packages never conflict.