Subtract seconds from datetime in python Subtract seconds from datetime in python python-3.x python-3.x

Subtract seconds from datetime in python


Using the datetime module indeed:

import datetimeX = 65result = datetime.datetime.now() - datetime.timedelta(seconds=X)

You should read the documentation of this package to learn how to use it!


Consider using dateutil.relativedelta, instead of datetime.timedelta.

>>> from datetime import datetime>>> from dateutil.relativedelta import relativedelta>>> now = datetime.now()>>> nowdatetime.datetime(2014, 6, 3, 22, 55, 9, 680637)>>> now - relativedelta(seconds=15)datetime.datetime(2014, 6, 3, 22, 54, 54, 680637)

In this case of a 15 seconds delta there is no advantage over using a stdlib timedelta, but relativedelta supports larger units such as months or years, and it may handle the general case with more correctness (consider for example special handling required for leap years and periods with daylight-savings transitions).


To expand on @julienc's answer, (in case it is helpful to someone)

If you allow X to accept positive or negatives, and, change the subtraction statement to an addition statement, then you can have a more intuitive (so you don't have to add negatives to negatives to get positives) time adjusting feature like so:

def adjustTimeBySeconds(time, delta):    return time + datetime.timedelta(seconds=delta)time = datetime.datetime.now()X = -65print(adjustTimeBySeconds(time, X))X = 65print(adjustTimeBySeconds(time, X))