Handling dates and times is a common requirement in programming, and Python provides powerful tools to manage them efficiently. Whether you're calculating time differences, formatting dates, or extracting months from datetime objects, Python's built-in modules make it easy.
In this comprehensive guide, we'll explore how to work with months in Python, covering:
datetime
Module for Date Handlingpytz
calendar
for Month OperationsBy the end, you'll be proficient in managing months in Python for various applications, from data analysis to web development.
datetime
Module for Date HandlingPython’s datetime
module is the foundation for working with dates and times. It provides several classes, including:
datetime.date
– Handles dates (year, month, day)
datetime.time
– Manages time (hour, minute, second)
datetime.datetime
– Combines date and time
datetime.timedelta
– Represents time differences
from datetime import datetime
current_date = datetime.now()
print(current_date) # Output: 2025-04-05 14:30:00.123456 (example)
print(f"Current month: {current_date.month}") # Output: 4 (April)
This retrieves the current month as an integer (1-12).
You can extract the month from a given date in multiple ways:
datetime
Objectdate_str = "2025-07-15"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
month = date_obj.month
print(month) # Output: 7
strftime
for Month Namemonth_name = date_obj.strftime("%B") # Full month name (e.g., "July")
month_short = date_obj.strftime("%b") # Short name (e.g., "Jul")
print(month_name, month_short) # Output: July Jul
Python’s strftime
method allows flexible date formatting:
Directive | Meaning | Example |
---|---|---|
%b |
Abbreviated month name | Jan , Feb |
%B |
Full month name | January , February |
%m |
Month as zero-padded number | 01 (Jan), 12 (Dec) |
Example:
today = datetime.now()
print(today.strftime("%B %d, %Y")) # Output: "April 05, 2025"
print(today.strftime("%b-%Y")) # Output: "Apr-2025"
You can compute differences between months using timedelta
and relativedelta
(from dateutil
).
timedelta
(Basic Differences)from datetime import timedelta
future_date = today + timedelta(days=60)
print(future_date.month) # Adds ~2 months (depends on days)
dateutil.relativedelta
(Precise Month Calculations)from dateutil.relativedelta import relativedelta
next_month = today + relativedelta(months=1)
print(next_month.strftime("%B")) # Output: "May"
This correctly handles month transitions, including year changes.
pytz
When working with global applications, time zones matter. The pytz
library helps:
import pytz
tz_ny = pytz.timezone("America/New_York")
ny_time = datetime.now(tz_ny)
print(ny_time.strftime("%B %d, %Y %Z")) # Output: "April 05, 2025 EDT"
calendar
for Month OperationsPython’s calendar
module provides additional month-related functions:
import calendar
month_days = calendar.monthrange(2025, 4)
print(month_days) # Output: (1, 30) → (Weekday of 1st April, total days)
month_cal = calendar.month(2025, 4)
print(month_cal)
# Output:
# April 2025
# Mo Tu We Th Fr Sa Su
# 1 2 3 4 5 6
# 7 8 9 10 11 12 13
# 14 15 16 17 18 19 20
# 21 22 23 24 25 26 27
# 28 29 30
data = [{"date": "2025-04-10", "value": 100}, {"date": "2025-05-15", "value": 200}]
filtered = [d for d in data if datetime.strptime(d["date"], "%Y-%m-%d").month == 4]
print(filtered) # Output: [{'date': '2025-04-10', 'value': 100}]
from collections import defaultdict
monthly_data = defaultdict(list)
for entry in data:
month = datetime.strptime(entry["date"], "%Y-%m-%d").strftime("%B")
monthly_data[month].append(entry["value"])
print(monthly_data) # Output: {'April': [100], 'May': [200]}
✅ Always use datetime.strptime
for parsing strings
✅ Prefer relativedelta
for month arithmetic
✅ Use pytz
or zoneinfo
(Python 3.9+) for time zones
✅ Store dates in ISO format (YYYY-MM-DD
) for consistency
Working with months in Python is straightforward thanks to the datetime
, calendar
, and third-party libraries like dateutil
and pytz
. Whether you need to extract, format, or calculate month differences, Python provides efficient solutions.
By mastering these techniques, you can handle date-related operations in data analysis, web apps, automation scripts, and more.