11

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?

Milan
  • 1,743
  • 2
  • 13
  • 36
user63503
  • 6,243
  • 14
  • 41
  • 44

2 Answers2

8

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 '
pyfunc
  • 65,343
  • 15
  • 148
  • 136
  • The question is how to convert the "00:03:12,200" string into the time object. I'm getting errors for the t = datetime.strptime("00:02:59,840", "%HH:%MM:%SS,mmm"). Says: ValueError: time data '00:02:59,840' does not match format '%HH:%MM:%SS,mmm' – user63503 Dec 06 '10 at 04:05
  • t = datetime.strptime("00:02:59", "%HH:%MM:%SS%mmm") or "%HH:%MM:%SS%,mmm" or "%HH:%MM:%SS,%mmm" -- all give the errors. I've got a comma after seconds, which don't know how to represent in the format string. – user63503 Dec 06 '10 at 04:13
  • For me when I do: t = datetime.strptime("00:02:59,840", "%HH:%MM:%SS,%f") it shows an error: ValueError: time data '00:02:59,840' does not match format '%HH:%MM:%SS,%f' – user63503 Dec 06 '10 at 04:20
  • OK, I shouldn't have used the double quotes. It works with single quotes! – user63503 Dec 06 '10 at 04:24
7

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:

icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • I've got specific timestamp format. How to make python to understand the string like '00:03:12,200' as time? – user63503 Dec 06 '10 at 04:07
  • By providing a format string to `strptime` that describes the format. Read the documentation that was provided. – Karl Knechtel Dec 06 '10 at 04:11
  • Yep, as Karl mentions, go to the above link, scroll to the end - you have all the specifiers you need there. – icyrock.com Dec 06 '10 at 04:15
  • Karl, I've read it. Still can't figure out how to describe that string with ":" between hours, minutes and seconds, and "," after the seconds. – user63503 Dec 06 '10 at 04:15
  • OK, try: %H:%M:%S,%f. Read this SOq: http://stackoverflow.com/questions/698223/how-can-i-parse-a-time-string-containing-milliseconds-in-it-with-python – icyrock.com Dec 06 '10 at 04:20