Ad – 728Γ—90
πŸ”§ Intermediate

Python datetime – Working with Dates and Times

Python's datetime module provides classes for manipulating dates and times. It is essential for applications involving scheduling, logging, age calculation, deadline tracking, or any time-based logic.

⏱️ 22 min read🎯 IntermediateπŸ“… Updated 2026

Basic datetime Objects

The datetime module provides: date (year/month/day), time (hour/min/sec), datetime (both combined), and timedelta (duration).

Python
from datetime import date, time, datetime, timedelta

# Current date and time
today = date.today()
now = datetime.now()

print(today)          # 2024-06-03
print(now)            # 2024-06-03 14:30:15.123456
print(now.year)       # 2024
print(now.month)      # 6
print(now.day)        # 3
print(now.hour)       # 14
β–Ά Output
2024-06-03 2024-06-03 14:30:15.123456 2024 6 3 14

Creating Specific Dates and Times

Create datetime objects for specific points in time.

Python
from datetime import datetime, date

# Specific date
birthday = date(1990, 7, 15)
print(birthday)  # 1990-07-15

# Specific datetime
event = datetime(2024, 12, 25, 18, 30, 0)
print(event)     # 2024-12-25 18:30:00

# From ISO string
d = datetime.fromisoformat("2024-06-15T09:00:00")
print(d)
β–Ά Output
1990-07-15 2024-12-25 18:30:00 2024-06-15 09:00:00

Formatting Dates – strftime()

Convert datetime to a string with custom format using strftime().

Python
from datetime import datetime

now = datetime.now()

print(now.strftime("%Y-%m-%d"))            # 2024-06-03
print(now.strftime("%d/%m/%Y"))            # 03/06/2024
print(now.strftime("%B %d, %Y"))           # June 03, 2024
print(now.strftime("%I:%M %p"))            # 02:30 PM
print(now.strftime("%A, %B %d, %Y"))       # Monday, June 03, 2024
β–Ά Output
2024-06-03 03/06/2024 June 03, 2024 02:30 PM Monday, June 03, 2024
Ad – 336Γ—280

Parsing Date Strings – strptime()

Convert a string into a datetime object.

Python
from datetime import datetime

# Parse date from string
date_str = "25 December 2024"
dt = datetime.strptime(date_str, "%d %B %Y")
print(dt)           # 2024-12-25 00:00:00

# Another format
dt2 = datetime.strptime("2024-06-15 14:30", "%Y-%m-%d %H:%M")
print(dt2)
β–Ά Output
2024-12-25 00:00:00 2024-06-15 14:30:00

Date Arithmetic with timedelta

timedelta represents a duration. Add or subtract it from dates.

Python
from datetime import datetime, timedelta

now = datetime.now()

# Add/subtract time
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
in_90_days = now + timedelta(days=90)

print(f"Tomorrow: {tomorrow.date()}")
print(f"Last week: {last_week.date()}")
print(f"In 90 days: {in_90_days.date()}")

# Difference between dates
birthday = datetime(1990, 7, 15)
age_days = (now - birthday).days
print(f"Days alive: {age_days}")
β–Ά Output
Tomorrow: 2024-06-04 Last week: 2024-05-27 In 90 days: 2024-09-01 Days alive: 12376