To add seconds to 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_future = now + timedelta(seconds=1)
sixty_seconds_in_future = now + timedelta(seconds=60)
one_hour_in_future = now + timedelta(seconds=3600)
print(now)
print(one_second_in_future)
print(sixty_seconds_in_future)
print(one_hour_in_future)
#Output:
2022-02-09 15:45:53.655282
2022-02-09 15:45:54.655282
2022-02-09 15:46:53.655282
2022-02-09 16: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 add seconds to a datetime variable.
With Python, we can easily add seconds to a date with the help of the datetime module.
To add seconds to a date in Python, we can use the timedelta() function from the datetime module.
Below is code that shows you how to add seconds to datetimes variables using Python.
from datetime import timedelta, datetime
now = datetime.now()
one_second_in_future = now + timedelta(seconds=1)
sixty_seconds_in_future = now + timedelta(seconds=60)
one_hour_in_future = now + timedelta(seconds=3600)
print(now)
print(one_second_in_future)
print(sixty_seconds_in_future)
print(one_hour_in_future)
#Output:
2022-02-09 15:45:53.655282
2022-02-09 15:45:54.655282
2022-02-09 15:46:53.655282
2022-02-09 16: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 subtract seconds, you can just subtract the call to the timedelta() function.
How to Add Seconds to a Date Variable With pandas in Python
If you are using the Python pandas module, we can add seconds to a datetime easily.
With pandas, to add seconds to a datetime, we use the DateOffset() function.
Below is an example of how to use pandas to add seconds to a datetime in Python.
import pandas as pd
startdate = "02/09/2022"
enddate = pd.to_datetime(startdate) + pd.DateOffset(seconds=60)
print(startdate)
print(enddate)
#Output:
2022-02-09 00:00:00
2022-02-09 00:01:00
Hopefully this article has been beneficial for you to learn how to add seconds to a datetime variable in Python.