Python Date/Datetime Arithmetic Examples: Adding, Subtracting, etc

Python Date/Datetime Arithmetic Examples: Adding, Subtracting, etc

Last updated:
Python Date/Datetime Arithmetic Examples:  Adding, Subtracting, etc
Source
Table of Contents

Unless otherwise stated, python v3.6+ is used

For other examples on how to use Python date/datetime objects, see Python Datetime Examples

All code for this post is available here: datetime-arithmetic.ipynb

Add seconds to Datetime

Add timedelta(seconds=N) to your datetime object

from datetime import datetime,timedelta

date_before = datetime.now()
# datetime.datetime(2022, 5, 8, 1, 52, 41, 804450)

date_after = date_before + timedelta(seconds=5)
# datetime.datetime(2022, 5, 8, 1, 52, 46, 804450)

Add days to date

Add timedelta(days=N) to your date object

from datetime import date,timedelta

date_before = date.today()
# datetime.date(2022, 5, 8)

date_after = date_before + timedelta(days=2)
# datetime.date(2022, 5, 10)

Datetime difference in seconds

Adding and subtracting Datetime objects gives you a TimeDelta object as result.

You can call .seconds (also hours, minutes, etc) on the TimeDelta object.

from datetime import datetime, timedelta

date_before = datetime.now()

# added 5 seconds
date_after = date_before + timedelta(seconds=5)

delta = date_after - date_before
# datetime.timedelta(seconds=5)

print(delta.seconds)
# 5