iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Dates

Dates and times live in the datetime module. Use datetime for points in time, timedelta for durations, date for dates without a time, and time for clocks without a date.

Now / today

PYTHON
from datetime import datetime, date, time, timedelta

now = datetime.now()
today = date.today()
print(now)            # 2026-06-06 14:32:11.123456
print(today)          # 2026-06-06

Arithmetic with timedelta

PYTHON
tomorrow = today + timedelta(days=1)
in_an_hour = now + timedelta(hours=1)
duration = datetime(2026, 7, 1) - datetime(2026, 1, 1)
print(duration.days)   # 181

Formatting & parsing

PYTHON
print(now.strftime('%Y-%m-%d %H:%M'))         # format
parsed = datetime.strptime('2026-06-06', '%Y-%m-%d')  # parse
print(now.isoformat())                         # ISO 8601

Common format codes

CodeMeans
%Y %m %d4-digit year, 2-digit month, 2-digit day
%H %M %S24-hr time
%A %BDay name, month name
%wDay of week as number (Sunday=0)

Time zones

Best practice: store everything as UTC; convert only for display.

PYTHON
from datetime import timezone
now_utc = datetime.now(timezone.utc)
print(now_utc.isoformat())
Tip: For full-featured timezone support and IANA names ("Australia/Sydney"), use the standard-library zoneinfo module (Python 3.9+).

Example

Example
from datetime import datetime, timedelta
now = datetime.now()
print(now.isoformat())
print((now + timedelta(days=7)).strftime('%Y-%m-%d'))
Try it Yourself »

Exercise

Get the current datetime.

from datetime import datetime now = datetime. ()

Test yourself

Q1. datetime.now() returns…
Q2. Best practice: store time in…
Q3. For IANA timezone names use…

Discussion

Loading…