Working with Dates and Times
Working with dates and times is a common task in Python. The datetime module provides classes for manipulating dates and times. This tutorial covers the basics of datetime, date, time, timedelta, and timezone handling.
The datetime Module
The datetime module is part of Python standard library. You do not need to install anything.
import datetime
Creating Dates and Times
Creating a Specific Date
Use the date class to create a specific date.
import datetime
## Create a specific date
d = datetime.date(2024, 12, 25)
print(d)
## 2024-12-25
Creating a Specific Time
Use the time class for times.
import datetime
## Create a specific time
t = datetime.time(14, 30, 0)
print(t)
## 14:30:00
Creating a datetime with Both Date and Time
Combine date and time into a datetime object.
import datetime
## Create a specific datetime
dt = datetime.datetime(2024, 12, 25, 14, 30, 0)
print(dt)
## 2024-12-25 14:30:00
Getting the Current Date and Time
Use the now() method.
import datetime
now = datetime.datetime.now()
print(now)
## 2024-03-07 10:15:30.123456
today = datetime.date.today()
print(today)
## 2024-03-07
Extracting Components
You can extract year, month, day, hour, minute, second from a datetime.
import datetime
now = datetime.datetime.now()
print(now.year) # 2024
print(now.month) # 3
print(now.day) # 7
print(now.hour) # 10
print(now.minute) # 15
print(now.second) # 30
Formatting Dates and Times
Use strftime to format datetime as string.
import datetime
now = datetime.datetime.now()
## Common format codes
print(now.strftime("%Y-%m-%d")) # 2024-03-07
print(now.strftime("%d/%m/%Y")) # 07/03/2024
print(now.strftime("%B %d, %Y")) # March 07, 2024
print(now.strftime("%I:%M %p")) # 10:15 AM
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2024-03-07 10:15:30
Parsing Strings to Dates
Use strptime to convert string to datetime.
import datetime
date_string = "2024-12-25 14:30:00"
dt = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(dt)
## 2024-12-25 14:30:00
Date Arithmetic with timedelta
Use timedelta for date arithmetic.
import datetime
## Add 7 days to a date
today = datetime.date.today()
one_week = datetime.timedelta(days=7)
next_week = today + one_week
print(next_week)
## 2024-03-14
## Subtract 30 days
thirty_days_ago = today - datetime.timedelta(days=30)
print(thirty_days_ago)
## 2024-02-06
Calculating Time Differences
You can subtract two dates or datetimes to get a timedelta.
import datetime
start = datetime.datetime(2024, 1, 1)
end = datetime.datetime(2024, 1, 15)
difference = end - start
print(difference)
## 14 days, 0:00:00
print(difference.days)
## 14
Timezones
Handle timezones with the zoneinfo module (Python 3.9+).
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
## Create timezone-aware datetime
now_utc = datetime.now(timezone.utc)
print(now_utc)
## 2024-03-07 10:15:30+00:00
## Convert to different timezone
now_pst = now_utc.astimezone(ZoneInfo("America/Los_Angeles"))
print(now_pst)
## 2024-03-07 02:15:30-08:00
Practical Examples
Age Calculator
import datetime
def calculate_age(birthdate):
today = datetime.date.today()
age = today.year - birthdate.year
# Check if birthday hasnt happened yet this year
if (today.month, today.day) < (birthdate.month, birthdate.day):
age -= 1
return age
birth = datetime.date(1990, 5, 15)
print(calculate_age(birth))
## 34 (if today is March 7, 2024)
Days Until Event
import datetime
def days_until(event_date):
today = datetime.date.today()
return (event_date - today).days
christmas = datetime.date(2024, 12, 25)
print(f"Days until Christmas: {days_until(christmas)}")
## Days until Christmas: 293
Common Mistakes
Forgetting timezone info
Always specify timezone when working with servers or multiple regions.
## Wrong: naive datetime
now = datetime.datetime.now()
## Right: timezone-aware
now = datetime.datetime.now(timezone.utc)
Using string comparison for dates
Always use datetime objects for comparison, not strings.
## Wrong
"2024-01-01" < "2024-12-31" # lexicographic comparison
## Right
datetime.date(2024, 1, 1) < datetime.date(2024, 12, 31) # proper date comparison
Next Steps
Now you know how to work with dates and times in Python. Practice by building a simple event countdown timer or a date difference calculator.
For more advanced date handling, explore the pandas library for time series data or the arrow library for easier timezone handling.