Subtract seconds from datetime in python

Question:

I have an int variable that are actually seconds (lets call that amount of seconds X). I need to get as result current date and time (in datetime format) minus X seconds.

Example

If X is 65 and current date is 2014-06-03 15:45:00, then I need to get the result 2014-06-03 15:43:45.

Environment

I’m doing this on Python 3.3.3 and I know I could probably use the datetime module but I haven’t had any success so far.

Asked By: rodrigocf

||

Answers:

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!

Answered By: julienc

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).

Answered By: wim

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))
Answered By: AlienFromCA
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.