Table of Contents

import datetime

import datetime is a Python import that provides date, time, and timezone handling. Use it for creating timestamps, calculating date differences, and formatting dates for display.

Example

# Python
# description: work with dates and times
 
from datetime import datetime, timedelta, date
 
# Current time
now = datetime.now()
print(now)  # 2025-08-24 15:30:45.123456
 
# Create specific date/time
d = datetime(2025, 12, 25, 10, 30)
print(d.year, d.month, d.day)
 
# Time differences
today = date.today()
tomorrow = today + timedelta(days=1)
week_ago = today - timedelta(weeks=1)
 
# Calculate duration between dates
delta = tomorrow - today
print(delta.days)  # 1
 
# Format for display
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 2025-08-24 15:30:45
 
# Parse date string
parsed = datetime.fromisoformat("2025-12-25T10:30:00")
print(parsed)

Common classes and methods