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?

2 Answers 2

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 ' 
Sign up to request clarification or add additional context in comments.

4 Comments

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'
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.
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'
OK, I shouldn't have used the double quotes. It works with single quotes!
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:

5 Comments

I've got specific timestamp format. How to make python to understand the string like '00:03:12,200' as time?
By providing a format string to strptime that describes the format. Read the documentation that was provided.
Yep, as Karl mentions, go to the above link, scroll to the end - you have all the specifiers you need there.
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.
OK, try: %H:%M:%S,%f. Read this SOq: stackoverflow.com/questions/698223/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.