Current Date and Time
datetime.now() returns the current local date and time. Access individual components like year, month, day, hour, minute, second.
from datetime import datetime
now = datetime.now()
print(now)
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
Try it Yourself โ
Using timedelta
timedelta represents a duration. Add or subtract it from a datetime to get future or past dates.
from datetime import datetime, timedelta
today = datetime.now()
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
print("Tomorrow:", tomorrow)
print("Last week:", last_week)
Try it Yourself โ
Formatting Dates with strftime
strftime() formats a datetime into a string. Common codes: %Y (year), %m (month), %d (day), %H (hour), %M (minute).
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)
friendly = now.strftime("%B %d, %Y at %I:%M %p")
print(friendly)
Try it Yourself โ