
Photo by the author Chatgpt
Entry
Python is built -in datetime The module can be easily considered a library to support the date and time of formatting and manipulation in the ecosystem. Most Python coders know creation datetime Objects, formatting them in strings and making basic arithmetic. However, this powerful module, sometimes with related libraries, such as calendarIt offers a lot of more functionalities outside the basics that can solve elaborate problems related to the date and sometimes with surprising ease.
This article applies to 10 useful – and perhaps surprising – things you can achieve thanks to Python datetime module. From the navigation of time zones to the calculation of specific speeches on weekdays, these examples show the versatility of the Python tool set.
1. Finding the day of the week
Apart from the fact that you only know the date, you often need to know the day of the week. . datetime The module makes this negligible. Everyone datetime The object has weekday() The method that returns the day of the week as an integer (Monday is 0, Sunday is 6) and strftime() A method that can format the date of showing the whole 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}")
Exit:
The date 2025-07-10 is a Thursday
2. Calculation of time to the future event
Have you ever needed a elementary counting time? WITH datetimeYou can easily calculate the time remaining until a specific date and future. By subtracting electricity datetime You get from the future timedelta The 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}")
Exit:
Time left until Fresh Year 2050: 8940 days, 16:05:52.120836
3. Working with time zones
Service of time zones is hard. AND naive datetime The object has no data in the time zone, a aware The object has this data. By means of pytz Library (or built -in zoneinfo In Python 3.9+) makes working with time time managed.
For example, you can apply the time of one time zone as a basis for conversion to another time zone in this way:
import datetime
from pytz import timezone
# Create a timezone-aware datetime for Fresh 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}")
Exit:
Fresh York Time: 2025-07-10 07:57:53.900220-04:00
London Time: 2025-07-10 12:57:53.900220+01:00
4. Receiving on the last day of the month
Determining the last day of the month is not simple because the months have a different number of days. You can write logic to handle 30/31 days with February (don’t forget about the ankle years!), Or you can apply a clever trick with datetime AND timedelta. The strategy is to find the first day 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}")
Exit:
The last day of February 2024 is: 2024-02-29
5. Calculation of the precise age
You can apply datetime To calculate someone’s age for the whole day. Logic consists in deducting birth dates from the current date, and then making a tiny correction to take into account whether the birthday of a person took place 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.")
Exit:
If alive today, Pablo Picasso would be 143 years aged.
6. Iteration for a number of dates
Sometimes you have to perform surgery for each day in a specific date range. You can easily loop the dates, starting from the date of the date and adding many times timedelta 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
Exit:
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 of the date from non -standard string formats
. strptime() The function is useful for converting strings into datetime Objects. It is extremely adaptable and can support a wide range of formats using specific format codes. This is necessary for data from various sources that may not apply the 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}")
Exit:
Parsed object 1: 1776-07-04 00:00:00
Parsed object 2: 1867-07-01 14:30:00
8. Finding the month of the month of the month
Do you want to know the date of the third Thursday in November? . calendar The module can be used next datetime To solve this. . monthcalendar() The function returns the matrix representing weeks of the month, which can then be analyzed.
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}")
Exit:
The third Thursday of Nov 2025 is: 2025-11-20
9. Winning the ISO weekly number
. ISO 8601 The standard defines the system for the week when the week starts on Monday. . isocalendar() The method returns a tiny -term year containing ISO year, week and weekday number for a given date.
Note that the date below is Thursday, and therefore it should result in the day of week 4. It should also be 28 weeks 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]}")
Exit:
Date: 2025-07-10
ISO Year: 2025
ISO Week Number: 28
ISO Weekday: 4
10. Adding or subtraction of working days
Calculating future dates when skipping weekends is a common business requirement. One sec datetime There is no built -in function for this, you can write a elementary auxiliary function with timedelta and 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
Python datetime The module is more than a elementary dates tool. It provides a adaptable and useful set of tools for handling almost any logic related to time. Understanding its basic elements - dateIN timeIN datetimeAND timedelta - And connecting them with calendar module or external libraries such as pytzYou can effectively and thoroughly solve elaborate problems with the real world.
Don't forget to check datetime modules documentation more. You may be surprised by what you can achieve.
Matthew Mayo (@ Matmayo13) Has a master's degree in computer science and a data extraction graduate diploma. As an editor managing kdnuggets & Statologyand the editor of the contribution in Machine learning championshipMatthew is aimed at providing elaborate concepts of data education. His professional interests include natural language processing, language models, machine learning algorithms and exploring the emerging artificial intelligence. He is powered by the mission of democratization of knowledge in the data science community. Matthew has been coding for 6 years.
