10 Surprising Things You Can Do with Python’s datetime Module

0
7



Image by Author | ChatGPT

 

Introduction

 
Python’s built-in datetime module can easily be considered the go-to library for handling date and time formatting and manipulation in the ecosystem. Most Python coders are familiar with creating datetime objects, formatting them into strings, and performing basic arithmetic. However, this powerful module, sometimes alongside related libraries such as calendar, offers a ton more functionality beyond the basics that can solve complex date and time-related problems with surprising ease.

This article looks at 10 useful — and perhaps surprising — things you can accomplish with Python’s datetime module. From navigating timezones to calculating specific weekday occurrences, these examples will demonstrate the versatility of Python’s date and time toolkit.

 

1. Finding the Day of the Week

 
Beyond just knowing the date, you often need to know the day of the week. The datetime module makes this trivial. Every datetime object has a weekday() method, which returns the day of the week as an integer (Monday is 0, Sunday is 6), and a strftime() method, which can format the date to show the full day name.

import datetime

# Pick a date
today = datetime.date(2025, 7, 10)

# Get the day of the week (Monday is 0)
day_of_week_num = today.weekday()
print(f"Day of the week (numeric): {day_of_week_num}")

# Get the full name of the day
day_name = some_date.strftime("%A")
print(f"The date {today} is a {day_name}")

 

Output:

The date 2025-07-10 is a Thursday

 

2. Calculating the Time Until a Future Event

 
Ever needed a simple countdown timer? With datetime, you can easily calculate the time remaining until a specific future date and time. By subtracting the current datetime from a future one, you get a timedelta object that represents the difference.

import datetime

# Define a future event
new_year_2050 = datetime.datetime(2050, 1, 1, 0, 0, 0)

# Get the current time
now = datetime.datetime.now()

# Calculate the difference
time_left = new_year_2050 - now

print(f"Time left until New Year 2050: {time_left}")

 

Output:

Time left until New Year 2050: 8940 days, 16:05:52.120836

 

3. Working with Timezones

 
Handling timezones is tricky. A naive datetime object has no timezone data, while an aware object does possess this data. Using the pytz library (or the built-in zoneinfo in Python 3.9+) makes working with timezones manageable.

For instance, you can use one timezone’s time as a base for conversion to another timezone like this:

import datetime
from pytz import timezone

# Create a timezone-aware datetime for New York
nyc_tz = timezone('America/New_York')
nyc_time = datetime.datetime.now(nyc_tz)
print(f"New York Time: {nyc_time}")

# Convert it to another timezone
london_tz = timezone('Europe/London')
london_time = nyc_time.astimezone(london_tz)
print(f"London Time: {london_time}")

 

Output:

New York Time: 2025-07-10 07:57:53.900220-04:00
London Time: 2025-07-10 12:57:53.900220+01:00

 

4. Getting the Last Day of a Month

 
Figuring out the last day of a month is not straightforward since months have different numbers of days. You could write logic to handle 30/31 days along with February (don’t forget about leap years!), or you could use a clever trick with datetime and timedelta. The strategy is to find the first day of the next month and then subtract one day.

import datetime

def get_last_day_of_month(year, month):
    # Handle month rollover for December -> January
    if month == 12:
        next_month_first_day = datetime.date(year + 1, 1, 1)
    else:
        next_month_first_day = datetime.date(year, month + 1, 1)
    
    # Subtract one day to get the last day of the current month
    return next_month_first_day - datetime.timedelta(days=1)

# Example: Get the last day of February 2024 (a leap year)
last_day = get_last_day_of_month(2024, 2)
print(f"The last day of February 2024 is: {last_day}")

 

Output:

The last day of February 2024 is: 2024-02-29

 

5. Calculating Your Precise Age

 
You can use datetime to calculate someone’s age down to the day. The logic involves subtracting the birthdate from the current date and then performing a small adjustment to account for whether the person’s birthday has occurred yet this year.

import datetime

def calculate_age(birthdate):
    today = datetime.date.today()
    age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
    return age

# Example usage
picasso_birthdate = datetime.date(1881, 10, 25)
picasso_age = calculate_age(picasso_birthdate)
print(f"If alive today, Pablo Picasso would be {picasso_age} years old.")

 

Output:

If alive today, Pablo Picasso would be 143 years old.

 

6. Iterating Through a Range of Dates

 
Sometimes you need to perform an operation for every day within a specific date range. You can easily loop through dates by starting with a date object and repeatedly adding a timedelta of one day until you reach the end date.

import datetime

start_date = datetime.date(2025, 1, 1)
end_date = datetime.date(2025, 1, 7)
day_delta = datetime.timedelta(days=1)

current_date = start_date
while current_date <= end_date:
    print(current_date.strftime('%Y-%m-%d, %A'))
    current_date += day_delta

 

Output:

2025-01-01, Wednesday
2025-01-02, Thursday
2025-01-03, Friday
2025-01-04, Saturday
2025-01-05, Sunday
2025-01-06, Monday
2025-01-07, Tuesday

 

7. Parsing Dates from Non-Standard String Formats

 
The strptime() function is useful for converting strings to datetime objects. It is incredibly flexible and can handle a wide variety of formats by using specific format codes. This is essential when dealing with data from different sources that may not use a standard ISO format.

import datetime

date_string_1 = "July 4, 1776"
date_string_2 = "1867-07-01 14:30:00"

# Parse the first string format
dt_object_1 = datetime.datetime.strptime(date_string_1, "%B %d, %Y")
print(f"Parsed object 1: {dt_object_1}")

# Parse the second string format
dt_object_2 = datetime.datetime.strptime(date_string_2, "%Y-%m-%d %H:%M:%S")
print(f"Parsed object 2: {dt_object_2}")

 

Output:

Parsed object 1: 1776-07-04 00:00:00
Parsed object 2: 1867-07-01 14:30:00

 

8. Finding the Nth Weekday of a Month

 
Do you want to know the date of the third Thursday in November? The calendar module can be used alongside datetime to solve this. The monthcalendar() function returns a matrix representing the weeks of a month, which you can then parse.

import calendar

# calendar.weekday() Monday is 0 and Sunday is 6
# calendar.Thursday is 3
cal = calendar.Calendar()

# Get a matrix of weeks for November 2025
month_matrix = cal.monthdatescalendar(2025, 11)

# Find the third Thursday
third_thursday = [week[calendar.THURSDAY] for week in month_matrix if week[calendar.THURSDAY].month == 11][2]

print(f"The third Thursday of Nov 2025 is: {third_thursday}")

 

Output:

The third Thursday of Nov 2025 is: 2025-11-20

 

9. Getting the ISO Week Number

 
The ISO 8601 standard defines a system for week numbering where a week starts on a Monday. The isocalendar() method returns a tuple containing the ISO year, week number, and weekday for a given date.

Note that the date below is a Thursday, and so should result in a day of the week of 4. It should also be the 28th week of the year.

import datetime

d = datetime.date(2025, 7, 10)
iso_cal = d.isocalendar()

print(f"Date: {d}")
print(f"ISO Year: {iso_cal[0]}")
print(f"ISO Week Number: {iso_cal[1]}")
print(f"ISO Weekday: {iso_cal[2]}")

 

Output:

Date: 2025-07-10
ISO Year: 2025
ISO Week Number: 28
ISO Weekday: 4

 

10. Adding or Subtracting Business Days

 
Calculating future dates while skipping weekends is a common business requirement. While datetime doesn’t have a built-in function for this, you can write a simple helper function using timedelta and the weekday() method.

import datetime

def add_business_days(start_date, num_days):
    current_date = start_date
    while num_days > 0:
        current_date += datetime.timedelta(days=1)
        # weekday() returns 5 for Saturday and 6 for Sunday
        if current_date.weekday() < 5:
            num_days -= 1
    return current_date

start = datetime.date(2025, 7, 10) # A Thursday
end = add_business_days(start, 13)

print(f"13 business days after {start} is {end}")

 

13 business days after 2025-07-10 is 2025-07-29

 

Wrapping Up

 
Python’s datetime module is more than just a simple tool for storing dates. It provides a flexible and useful set of tools for handling almost any time-related logic imaginable. By understanding its core components — date, time, datetime, and timedelta — and combining them with the calendar module or external libraries like pytz, you can solve complex real-world problems efficiently and accurately.

Don’t forget to check out the datetime module’s documentation for more. You might be surprised at what you can accomplish.
 
 

Matthew Mayo (@mattmayo13) holds a master’s degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets & Statology, and contributing editor at Machine Learning Mastery, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.