Subtract seconds from datetime in python

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

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.now()
>>> now
datetime.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).


Using the datetime module indeed:

import datetime

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

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


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 = -65
print(adjustTimeBySeconds(time, X))
X = 65
print(adjustTimeBySeconds(time, X))