Python's datetime Module: Master the Art of Time and Dates
Documentation: The complete and reliable documentation for the datetime module can be found on the official Python website: docs.python.org
Key Classes of the datetime Module
This module provides several closely related classes that represent different aspects of time:
| date | Represents a date, consisting of the year, month, and day. Useful when you only need to work with the calendar date without considering the time. |
| time | Represents a time, consisting of the hour, minute, second, and microsecond. Often used to represent fixed times of the day. |
| datetime | The most frequently used class, a combination of date and time, storing complete information about the date and time of an event. |
| timedelta | Represents the difference (interval) between two date, time, or datetime instances. It is essential for adding and subtracting time. |
| tzinfo | An abstract base class used for handling time zones, allowing the creation of "aware" objects, as opposed to "naive" objects, which contain no time zone information. |
Example 1: Digital Clock (HH:MM:SS)
To create a digital clock simulation, we use the datetime.now() method to get the current moment and strftime() (string format time) to format it. Note that we import the time module only to use the sleep() function to pause the loop for 1 second.
from datetime import datetime
import time
def simple_clock(seconds=5):
"""Displays the current time in HH:MM:SS format and refreshes every second."""
print(f"--- Clock running for {seconds} seconds ---")
# Format codes: %H (Hour 24h), %M (Minute), %S (Second)
time_format = "%H:%M:%S"
for _ in range(seconds):
now = datetime.now()
formatted_time = now.strftime(time_format)
# Using '\r' allows overwriting the previous line in the console
print(f"Current time: {formatted_time}", end='\r')
time.sleep(1)
print("\n--- Clock finished ---")
# Calling the function
simple_clock(10)
| Source: | Name: |
|---|---|
| Download Center | post_28_1en |
Example 2: Elegant Date Display and Flexible Formatting
The power of the datetime module lies in its versatile formatting. The strftime() method transforms a datetime object into a readable string using special directives.
| %A | Full weekday name. | Tuesday |
| %d | Day of the month (zero-padded). | 07 |
| %B | Full month name. | October |
| %Y | Year with four digits. | 2025 |
| %j | Day of the year (001-366). | 280 |
from datetime import datetime
# Get the full datetime object
now = datetime.now()
# Creating an elegant datestamp
# Using appropriate directives for the format "Today is: Tuesday, October 07 2025"
elegant_datestamp = now.strftime("Today is: %A, %B %d %Y")
print("\n--- Elegant Datestamp ---")
print(elegant_datestamp)
# Another example: Abbreviated international format + Day of the Year
tech_datestamp = now.strftime("%Y-%m-%d (Day of year: %j)")
print(f"Technical format: {tech_datestamp}")
input('\nPress - Enter\n')
| Source: | Name: |
|---|---|
| Download Center | post_28_2en |
Example 3: Time Arithmetic with timedelta
The timedelta class is the heart of time operations, allowing for the precise addition or subtraction of time intervals (days, hours, minutes, seconds) from a datetime object.
from datetime import datetime, timedelta
today = datetime.now()
# Calculate the date 10 days and 12 hours from now
in_10_days = today + timedelta(days=10, hours=12)
# Calculate the date 3 weeks ago
three_weeks_ago = today - timedelta(weeks=3)
print("\n--- Time Operations (timedelta) ---")
print(f"Today: {today.strftime('%Y-%m-%d %H:%M')}")
print(f"In 10 days and 12h: {in_10_days.strftime('%Y-%m-%d %H:%M')}")
print(f"3 weeks ago: {three_weeks_ago.strftime('%Y-%m-%d %H:%M')}")
# Calculate the difference (timedelta) between two dates
created_date = datetime(year=2023, month=1, day=14, hour=21)
difference = today - created_date
print(f"\nDifference since 01/15/2023 (21:00): {difference.days} days and {difference.seconds // 3600} hours.")
input('\nPress - Enter\n')
| Source: | Name: |
|---|---|
| Download Center | post_28_3en |
Summary
The datetime module is a versatile and powerful component of Python's standard library. Mastering datetime.now(), strftime() for formatting, and timedelta for time arithmetic allows for effective handling of nearly every time-related scenario in your applications. While time zone handling (tzinfo) might occasionally require external libraries (like pytz or dateutil for greater convenience), the datetime module itself provides a solid foundation for all basic operations.
Code Quality & Security at Kajotte Studio
Python Learning Lab: Datetime Module - Every script in this repository is automatically verified via GitHub Actions to ensure the highest educational standards.
👇
▒ Blog Guide: All Programming Posts in One Place. ▹ See