To subtract seconds from a datetime using Python, the easiest way is to use the Python timedelta() function from the datetime module.

from datetime import timedelta, datetime

now = datetime.now()

one_second_in_past = now - timedelta(seconds=1)
sixty_seconds_in_past = now - timedelta(seconds=60)
one_hour_in_past = now - timedelta(seconds=3600)

print(now)
print(one_second_in_past)
print(sixty_seconds_in_past)
print(one_hour_in_past)

#Output:
2022-09-29 15:45:53.655282
2022-09-29 15:45:52.655282
2022-09-29 15:44:53.655282
2022-09-29 14:45:53.655282

When working with data in Python, many times we are working with datetimes. Being able to manipulate and change dates easily is very important for efficient processing.

One such change is to be able to subtract seconds from a datetime variable.

With Python, we can easily subtract seconds from a date with the help of the datetime module.

To subtract seconds from a date in Python, we can use the timedelta() function from the datetime module.

Below is code that shows you how to subtract seconds from datetime variables using Python.

from datetime import timedelta, datetime

now = datetime.now()

one_second_in_past = now - timedelta(seconds=1)
sixty_seconds_in_past = now - timedelta(seconds=60)
one_hour_in_past = now - timedelta(seconds=3600)

print(now)
print(one_second_in_past)
print(sixty_seconds_in_past)
print(one_hour_in_past)

#Output:
2022-09-29 15:45:53.655282
2022-09-29 15:45:52.655282
2022-09-29 15:44:53.655282
2022-09-29 14:45:53.655282

Note, here we need to use datetime.now(), and we can’t use date.today() because date won’t have the time associated with it.

If you want to add seconds, you can just add the call to the timedelta() function.

How to Subtract Seconds from a Date Variable With pandas in Python

If you are using the Python pandas module, we can subtract seconds from a datetime easily.

With pandas, to subtract seconds from a datetime, we use the DateOffset() function.

Below is an example of how to use pandas to subtract seconds from a datetime in Python.

import pandas as pd

startdate = "09/29/2022"
enddate = pd.to_datetime(startdate) - pd.DateOffset(seconds=60)

print(startdate)
print(enddate)

#Output:
2022-09-29 00:00:00
2022-09-28 23:59:00

Hopefully this article has been beneficial for you to learn how to subtract seconds from a datetime variable in Python.

Categorized in:

Python,

Last Update: March 11, 2024