Skip to content
Python

Date Handling

Handle dates and times with datetime.

By EZ4Code Team
datetimedate

Code

from datetime import datetime, timedelta, timezone

now = datetime.now()
utc_now = datetime.now(timezone.utc)

# Format
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# Parse
dt = datetime.strptime("2024-01-15", "%Y-%m-%d")

# Time difference
future = now + timedelta(days=7)
diff = future - now
print(diff.days)

# Timezone conversion
tz = timezone(timedelta(hours=8))
print(datetime.now(tz))

Explanation

datetime provides date formatting, parsing, arithmetic, and timezone handling.

More Python Snippets