Codectionary / Developer documentation / Python

datetime Module

The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.

Syntax

from datetime import datetime

Examples

Getting the Current Date and Time

Retrieving the current moment.

from datetime import datetime

now = datetime.now()
print(now)              # 2026-08-08 14:30:00.123456
print(now.year)         # 2026
print(now.month)        # 8
print(now.day)          # 8

Formatting Dates

Converting a datetime object into a custom-formatted string with strftime().

from datetime import datetime

now = datetime.now()

print(now.strftime("%Y-%m-%d"))         # 2026-08-08
print(now.strftime("%d/%m/%Y"))         # 08/08/2026
print(now.strftime("%B %d, %Y"))        # August 08, 2026
print(now.strftime("%H:%M:%S"))         # 14:30:00

Parsing Dates from Strings

Converting formatted text back into a datetime object with strptime().

from datetime import datetime

date_string = "2026-03-15"
parsed = datetime.strptime(date_string, "%Y-%m-%d")

print(parsed)          # 2026-03-15 00:00:00
print(parsed.year)     # 2026

Date Arithmetic with timedelta

Adding or subtracting durations from a date.

from datetime import datetime, timedelta

today = datetime.now()
next_week = today + timedelta(days=7)
ten_days_ago = today - timedelta(days=10)

print(next_week.strftime("%Y-%m-%d"))
print(ten_days_ago.strftime("%Y-%m-%d"))

difference = next_week - today
print(difference.days)  # 7

Best practices

  • Use strftime() format codes (%Y, %m, %d, %H, %M, %S) consistently - refer to the documentation rather than guessing the codes
  • Use timedelta for date arithmetic instead of manually calculating days, which quickly gets complicated around month/year boundaries
  • Store and compare dates as datetime objects rather than strings whenever possible, converting to text only for final display
  • Be mindful of time zones for applications that matter across regions - the standard datetime is naive by default and does not account for them

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading