Member-only story

Mastering Date and Time Arithmetic in Python: Your Essential Guide

Learn How to Perform Arithmetic Operations with Dates and Times Like a Pro

Max N
2 min readApr 7, 2024

Ever wondered how to add or subtract dates and times in Python? Look no further! In this guide, we’ll explore how to perform arithmetic operations with dates and times effortlessly.

Understanding Date and Time Arithmetic

Manipulating dates and times in Python involves various arithmetic operations, such as addition, subtraction, and comparison. Let’s delve into each operation with practical examples.

Adding and Subtracting Time

Adding or subtracting time from a datetime object is a common task in many applications. Python’s timedelta class makes it easy to achieve this:

import datetime

# Current datetime
now = datetime.datetime.now()

# Adding 3 days
future_date = now + datetime.timedelta(days=3)

# Subtracting 1 week
past_date = now - datetime.timedelta(weeks=1)

print("Future Date:", future_date)
print("Past Date:", past_date)

Calculating Time Differences

You can calculate the difference between two datetime objects using subtraction, resulting in a timedelta object:

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet