Site Tools


import-datetime

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

  • datetime.now(): current date and time
  • date.today(): current date
  • datetime(year, month, day, hour, minute, second): create specific datetime
  • timedelta(days=0, seconds=0, hours=0, ...): time duration
  • dt.strftime(format): format as string
  • datetime.fromisoformat(string): parse ISO format
  • dt.year, dt.month, dt.day: components
  • dt.hour, dt.minute, dt.second: time components
import-datetime.md · Last modified: by 127.0.0.1