Skip to content

Q&A · Answered

How to work with datetime in Python

asked 9 months, 3 weeks ago 1413 views 1 answer
14

Working with dates and times in Python is confusing. How do I parse, format, and manipulate dates?

1 Answer

One accepted
28

Accepted answer

Not confirmed since it was written, 9 months, 3 weeks ago

Basic datetime operations

from datetime import datetime, timedelta

# Get current datetime
now = datetime.now()

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

# Format datetime to string
date_string = dt.strftime('%B %d, %Y')  # January 15, 2024

# Date arithmetic
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)

Working with timezones

from datetime import timezone
import pytz

# UTC time
utc_now = datetime.now(timezone.utc)

# Specific timezone
tz = pytz.timezone('America/New_York')
local_time = datetime.now(tz)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.