开发者

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?


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 '


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜