datetime (Python module)

Comprehensive guide to Python’s datetime module: how to create, compare, and format dates and times, with practical examples using strftime, strptime, and timedelta.

« Back to Glossary Index

The datetime module is a built-in Python library used to manage dates and times efficiently and accurately.
It provides classes to represent dates (date), times (time), date-time combinations (datetime), and time intervals (timedelta), along with functions to compare, add, subtract, format, and convert temporal values.

It is essential for tasks such as:

  • Logging events and timestamps
  • Performing time difference calculations
  • Converting between date/time formats
  • Developing scheduling or real-time applications
Minimalist icon showing a calendar with highlighted squares and a clock, representing Python’s datetime module for date and time management.
Minimalist icon showing a calendar with highlighted squares and a clock, representing Python’s datetime module for date and time management.

Code examples

from datetime import datetime, timedelta

# Current date and time
now = datetime.now()
print("Now:", now)

# Custom format
print(now.strftime("%d/%m/%Y %H:%M"))

# Future date (+7 days)
future = now + timedelta(days=7)
print("In one week:", future.strftime("%d/%m/%Y"))

Additional notes

  • strftime() → converts a datetime object into a formatted string.
  • strptime() → parses a string into a datetime object.
  • timedelta allows arithmetic operations on date and time values.
« Back to Glossary Index