Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding seconds to datetime [duplicate]

I'm struggling to add different amounts of seconds to a timestamp.

Let's suppose I want to add 1136 seconds to 2016-12-02 13:26:49. This is what I have thus far:

import datetime

if __name__ == '__main__':
    timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
    offset = 1140
    m, s = divmod(offset, 60)
    h, m = divmod(m, 60)

I saw in another post something similar to what I want, but that is not for Python.

Should I use datetime.datetime.combine()?

I have a big amount of data and I do not want to manually input the date for every sum.

Thank you in advance for any help.

like image 428
Annemie 27 Avatar asked Jan 09 '17 15:01

Annemie 27


2 Answers

You could use timedelta to add seconds to datetime object.

>>> import datetime
>>> now = datetime.datetime.now()
>>> now 
datetime.datetime(2017, 1, 9, 16, 16, 12, 257210)
>>> now + datetime.timedelta(seconds=1136)
datetime.datetime(2017, 1, 9, 16, 22, 12, 257210)
>>> 
like image 83
Maurice Meyer Avatar answered Oct 09 '22 23:10

Maurice Meyer


Simply add a timedelta to the timestamp:

timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
d = datetime.timedelta(seconds=1136)
new_timestamp = timestamp+d

Running this in the console:

$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
>>> d = datetime.timedelta(seconds=1136)
>>> new_timestamp = timestamp+d
>>> new_timestamp
datetime.datetime(2016, 12, 2, 13, 45, 45)

So the result is December 12, 2016 at 13:45:45.

like image 40
Willem Van Onsem Avatar answered Oct 09 '22 22:10

Willem Van Onsem