Skip to content

Instantly share code, notes, and snippets.

@andreasvc
Last active March 30, 2020 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreasvc/8c7c06bc8c4e3f36744caa0cb1ccdb81 to your computer and use it in GitHub Desktop.
Save andreasvc/8c7c06bc8c4e3f36744caa0cb1ccdb81 to your computer and use it in GitHub Desktop.
import datetime
def addseconds(timestamp, seconds):
"""Take timestamp as string and add seconds to it.
>>> addseconds('00:01:45,667', 1)
'00:01:46,667'
>>> addseconds('00:01:45,667', 0.5)
'00:01:46,167'
"""
fmt = '%Y-%m-%d %H:%M:%S,%f'
# American format requires dot instead of comma
# Use datetime with a dummy date because datetime.time does not allow
# adding or subtracting.
x = datetime.datetime.strptime('2000-01-01 ' + timestamp, fmt)
y = datetime.timedelta(seconds=seconds)
x += y
# Turn time component back into string
newtimestamp = x.time().strftime('%H:%M:%S,%f')
# strip off last three digits, and put comma back
return newtimestamp[:-3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment