Basic datetime Objects
The datetime module provides: date (year/month/day), time (hour/min/sec), datetime (both combined), and timedelta (duration).
Python
from datetime import date, time, datetime, timedelta
# Current date and time
today = date.today()
now = datetime.now()
print(today) # 2024-06-03
print(now) # 2024-06-03 14:30:15.123456
print(now.year) # 2024
print(now.month) # 6
print(now.day) # 3
print(now.hour) # 14βΆ Output
2024-06-03
2024-06-03 14:30:15.123456
2024
6
3
14Creating Specific Dates and Times
Create datetime objects for specific points in time.
Python
from datetime import datetime, date
# Specific date
birthday = date(1990, 7, 15)
print(birthday) # 1990-07-15
# Specific datetime
event = datetime(2024, 12, 25, 18, 30, 0)
print(event) # 2024-12-25 18:30:00
# From ISO string
d = datetime.fromisoformat("2024-06-15T09:00:00")
print(d)βΆ Output
1990-07-15
2024-12-25 18:30:00
2024-06-15 09:00:00Formatting Dates β strftime()
Convert datetime to a string with custom format using strftime().
Python
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # 2024-06-03
print(now.strftime("%d/%m/%Y")) # 03/06/2024
print(now.strftime("%B %d, %Y")) # June 03, 2024
print(now.strftime("%I:%M %p")) # 02:30 PM
print(now.strftime("%A, %B %d, %Y")) # Monday, June 03, 2024βΆ Output
2024-06-03
03/06/2024
June 03, 2024
02:30 PM
Monday, June 03, 2024Ad β 336Γ280
Parsing Date Strings β strptime()
Convert a string into a datetime object.
Python
from datetime import datetime
# Parse date from string
date_str = "25 December 2024"
dt = datetime.strptime(date_str, "%d %B %Y")
print(dt) # 2024-12-25 00:00:00
# Another format
dt2 = datetime.strptime("2024-06-15 14:30", "%Y-%m-%d %H:%M")
print(dt2)βΆ Output
2024-12-25 00:00:00
2024-06-15 14:30:00Date Arithmetic with timedelta
timedelta represents a duration. Add or subtract it from dates.
Python
from datetime import datetime, timedelta
now = datetime.now()
# Add/subtract time
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
in_90_days = now + timedelta(days=90)
print(f"Tomorrow: {tomorrow.date()}")
print(f"Last week: {last_week.date()}")
print(f"In 90 days: {in_90_days.date()}")
# Difference between dates
birthday = datetime(1990, 7, 15)
age_days = (now - birthday).days
print(f"Days alive: {age_days}")βΆ Output
Tomorrow: 2024-06-04
Last week: 2024-05-27
In 90 days: 2024-09-01
Days alive: 12376