Python Standard Library

Published: November 13, 2025 • Language: python • Chapter: 6 • Sub: 2 • Level: beginner

python

Chapter 6: Python Standard Library

Sub-Chapter: Date and Time — Managing Temporal Information

Time is a critical aspect of almost every software system — from event logging and scheduling to analytics and financial transactions.
Python’s datetime module provides a complete suite of classes for representing, manipulating, and formatting dates, times, durations, and time zones.


🕒 1. Importing the datetime Module

import datetime

The module provides several key classes:

  • datetime.date — represents a calendar date (year, month, day)
  • datetime.time — represents time of day (hours, minutes, seconds)
  • datetime.datetime — combines both date and time
  • datetime.timedelta — represents the difference between two datetime objects
  • datetime.timezone — represents time zone information

📅 2. Getting the Current Date and Time

from datetime import datetime, date, time

current_datetime = datetime.now()
current_date = date.today()
current_time = datetime.now().time()

print(current_datetime)
print(current_date)
print(current_time)

Output:

2025-10-26 13:42:10.145312
2025-10-26
13:42:10.145312

🧱 3. Creating Specific Dates and Times

You can manually create datetime, date, or time objects:

from datetime import datetime, date, time

my_date = date(2024, 12, 25)
my_time = time(14, 30, 0)
my_datetime = datetime(2024, 12, 25, 14, 30, 0)

Each object can be accessed with properties like .year, .month, .day, .hour, etc.

print(my_datetime.year, my_datetime.hour)

🧮 4. Date and Time Arithmetic

You can add or subtract timedelta objects to perform arithmetic:

from datetime import datetime, timedelta

today = datetime.now()
future = today + timedelta(days=7, hours=3)
difference = future - today

print("One week later:", future)
print("Difference in days:", difference.days)

timedelta also supports seconds, minutes, weeks, and microseconds.


📆 5. Formatting and Parsing Dates

You can format datetime objects to strings using strftime() and parse strings back into datetimes with strptime().

from datetime import datetime

now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
parsed = datetime.strptime("2025-10-26 14:30:00", "%Y-%m-%d %H:%M:%S")

print(formatted)
print(parsed)

Common strftime and strptime Directives

Directive Meaning Example
%Y Year (4 digits) 2025
%m Month (01–12) 10
%d Day of month 26
%H Hour (00–23) 13
%M Minute (00–59) 45
%S Second (00–59) 09
%a Abbreviated weekday name Sun
%A Full weekday name Sunday
%b Abbreviated month name Oct
%B Full month name October
%Z Time zone name UTC

🌐 6. Working with Time Zones

Python distinguishes between naive and aware datetime objects.

  • Naive objects have no timezone info.
  • Aware objects include timezone data and support conversions.

Using pytz (3rd-party library)

from datetime import datetime
import pytz

utc = pytz.UTC
eastern = pytz.timezone("US/Eastern")

now_utc = datetime.now(utc)
now_eastern = now_utc.astimezone(eastern)

print(now_utc.strftime("%Y-%m-%d %H:%M:%S %Z"))
print(now_eastern.strftime("%Y-%m-%d %H:%M:%S %Z"))

Using zoneinfo (Python 3.9+ built-in)

from datetime import datetime
from zoneinfo import ZoneInfo

now = datetime.now(ZoneInfo("Asia/Tehran"))
print(now.strftime("%Y-%m-%d %H:%M:%S %Z"))

📦 7. ISO 8601 Format

Python supports the international ISO 8601 format by default.

from datetime import datetime

now = datetime.now()
iso_str = now.isoformat()
parsed = datetime.fromisoformat(iso_str)

print(iso_str)
print(parsed)

Output:

2025-10-26T13:52:15.246352
2025-10-26 13:52:15.246352

⏰ 8. Example — Calculating Age and Duration

from datetime import datetime

birth = datetime(1995, 5, 10)
age = datetime.now() - birth
years = age.days // 365

print(f"You are approximately {years} years old.")

Example: Countdown Timer

from datetime import datetime, timedelta

event_date = datetime(2025, 12, 31, 23, 59)
time_left = event_date - datetime.now()

print(f"Days until New Year: {time_left.days}")

🧰 9. Using dateutil for Flexible Parsing

For non-standard formats or natural language strings, use python-dateutil:

from dateutil import parser

dt = parser.parse("Oct 26, 2025 2:45 pm")
print(dt)

Output:

2025-10-26 14:45:00

The dateutil library automatically detects formats — no need for manual patterns.


📜 10. Real-World Example — Logging and Scheduling

from datetime import datetime, timedelta

class Scheduler:
    def __init__(self):
        self.events = []

    def schedule(self, name, delay_minutes):
        event_time = datetime.now() + timedelta(minutes=delay_minutes)
        self.events.append((name, event_time))
        print(f"Event '{name}' scheduled for {event_time.strftime('%H:%M:%S')}")

scheduler = Scheduler()
scheduler.schedule("Backup", 30)
scheduler.schedule("Report Generation", 90)

🧭 11. Best Practices for Working with Dates and Times

✅ Always use UTC internally; convert to local time only for display.
✅ Use timezone-aware datetimes to avoid errors in global applications.
✅ Prefer datetime.now(tz=...) over naive datetime.now().
✅ Use isoformat() and fromisoformat() for standard storage.
✅ For recurring events or calendars, use timedelta instead of loops.
✅ Leverage dateutil or zoneinfo instead of hardcoding offsets.


📊 12. UML-Style Diagram of datetime Classes

+------------------+
|  datetime.date   |
+------------------+
| year, month, day |
| + today()        |
| + fromisoformat()|
+------------------+
          ↑
          |
+------------------+
| datetime.datetime|
+------------------+
| date + time + tz |
| + now(), utcnow()|
| + strftime()     |
| + strptime()     |
| + isoformat()    |
+------------------+
          |
          ↓
+------------------+
| datetime.timedelta|
+------------------+
| days, seconds, etc |
| + total_seconds()  |
+------------------+

🧾 Summary

  • Python’s datetime module supports full control over dates, times, and time zones.
  • strftime and strptime handle formatting and parsing.
  • timedelta enables arithmetic operations and scheduling logic.
  • zoneinfo and pytz allow timezone conversions.
  • Always handle time explicitly and consistently — especially in distributed or global applications.

By mastering Python’s date and time tools, you’ll be equipped to build precise, timezone-aware, and reliable applications — from simple timers to complex scheduling systems.