Python: How to subtract/add a duration to a timestamp

Updated: February 13, 2024 By: Guest Contributor Post a comment

Introduction

Working with dates and times is a common task in many Python applications. Whether you’re developing a scheduling app, analyzing time-series data, or simply logging events with their timestamps, understanding how to manipulate dates and times is essential. This tutorial will walk you through the process of adding to or subtracting a duration from a timestamp, using Python’s built-in modules.

Python provides several modules for dealing with dates and times, notably datetime and dateutil. The datetime module is part of Python’s standard library and provides classes for manipulating dates and times easily. The dateutil module, on the other hand, is a third-party extension that offers additional functionality, including the parsing of dates from strings and easy computation of relative deltas.

Understanding Timestamps

A timestamp is a way to track time as a running total of seconds. In Python, timestamps are commonly represented as the number of seconds since the Unix epoch (00:00:00 UTC on January 1, 1970). You can also work with more human-readable datetime objects in Python, which can be converted to and from timestamps when necessary.

Let’s start by exploring how to work with timestamps and datetime objects in Python.

Getting the Current Timestamp

import datetime

now = datetime.datetime.now()
current_timestamp = now.timestamp()
print(f'Current timestamp: {current_timestamp}')

Converting a Timestamp to a Datetime Object

from datetime import datetime

timestamp = 1609459200  # Example timestamp for January 1, 2021
converted_datetime = datetime.fromtimestamp(timestamp)
print(f'Converted datetime: {converted_datetime}')

Adding and Subtracting Durations

Now that you have a basic understanding of working with datetime objects and timestamps, let’s focus on the core topic of this tutorial: adding and subtracting durations from these objects.

Using timedelta for Duration

The datetime module provides the timedelta class, which represents a duration, the difference between two dates or times. timedelta is incredibly useful for adding or subtracting time intervals from datetime objects.

Example: Adding 2 days to the current datetime

from datetime import datetime, timedelta

now = datetime.now()
two_days = timedelta(days=2)
future_date = now + two_days
print(f'Future date: {future_date}')

Subtracting 3 hours from the current datetime

from datetime import datetime, timedelta

now = datetime.now()
three_hours = timedelta(hours=-3)
past_date = now + three_hours
print(f'Past date: {past_date}')

Working with dateutil.relativedelta

For more complex time manipulations, such as adding months or years (which aren’t supported by timedelta due to variable lengths), the dateutil module’s relativedelta function comes into play.

First, install the dateutil package (if not already installed):

pip install python-dateutil

Example: Adding 1 year and 2 months to a datetime object

from datetime import datetime
from dateutil.relativedelta import relativedelta

some_date = datetime(2020, 1, 1)
modified_date = some_date + relativedelta(years=1, months=2)
print(f'Modified date: {modified_date}')

Converting Between Timestamps and datetime Objects

After modifying a datetime object by adding or subtracting a duration, you might need to convert it back into a timestamp. This is especially useful when dealing with systems or APIs that expect timestamp values.

Example: Converting a modified datetime object back to a timestamp

from datetime import datetime
from dateutil.relativedelta import relativedelta

modified_date = datetime(2022, 3, 10) + relativedelta(days=5)
modified_timestamp = modified_date.timestamp()
print(f'Modified timestamp: {modified_timestamp}')

Conclusion

In this tutorial, you’ve learned how to add or subtract durations from datetime objects and timestamps in Python, using both the datetime module’s timedelta class and the dateutil module’s relativedelta. These tools are essential for any Python developer working with time-related data, offering both simplicity and flexibility in handling time intervals.

Remember, practice is key to mastering these concepts. Consider exploring these examples further and integrating them into your own Python projects to gain a deeper understanding of date and time manipulations.