Member-only story
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: