14
Working with dates and times in Python is confusing. How do I parse, format, and manipulate dates?
Loading...
Q&A · Answered
Working with dates and times in Python is confusing. How do I parse, format, and manipulate dates?
Accepted answer
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)
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)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.