Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the Python code to add time to a specific timestamp?

Trying to figure out datetime module and need some help.

I've got a string which looks like this:

00:03:12,200 --> 00:03:14,316

(that is hours:minutes:seconds,milliseconds) and need to add let's say 10 seconds to each timestamp. To have as output:

00:03:22,200 --> 00:03:24,316

What would be the Python code to do that?

like image 526
user63503 Avatar asked Dec 06 '10 03:12

user63503


2 Answers

To parse time, use strptime

>>> x = '00:03:12,200 --> 00:03:14,316'
>>> x1 = x.split('-->')
>>> x1
['00:03:12,200 ', ' 00:03:14,316']
>>> t1 = datetime.datetime.strptime(x1[0], '%H:%M:%S,%f ')
>>> t1
datetime.datetime(1900, 1, 1, 0, 3, 12, 200000)

use timedelta

>>> t = datetime.timedelta(seconds=1)
>>> t
datetime.timedelta(0, 1)
>>> 
>>> t1 + t
datetime.datetime(1900, 1, 1, 0, 3, 13, 200000)
>>> k = t1 + t

Reconvert to string

>>> k.strftime('%H:%M:%S,%f ')
'00:03:13,200000 '
like image 73
pyfunc Avatar answered Sep 19 '22 01:09

pyfunc


To add 10 seconds, you can use this:

datetime.datetime.now() + datetime.timedelta(seconds=10)

To parse the above, you can use strptime:

datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")

Take a look here for more details:

  • http://docs.python.org/library/datetime.html
like image 38
icyrock.com Avatar answered Sep 23 '22 01:09

icyrock.com