Jump to content

Python: Time-string


LEO-oo-

Recommended Posts

I have a string with a time stamp:

time = "00:20:30" # HH:MM:SS

How to add 4 seconds to this string? Thanks a lot!

You probably could do some split() magic and add 4 seconds to the last part.

More convient would be to split it and convert completely to seconds and just format the output string.

Not sure if the datetime[1] module is very usable for this, but it's worth a look.

[1] http://docs.python.org/library/datetime.html

Link to comment
Share on other sites

Something like this will work. I've broken it up into a function to make it a bit cleaner, and a bit more general.

def add_seconds(timestring,n):
	h,m,s = map(int,timestring.split(":"))
	ts = s + 60*m + 60*60*h + n
	h,ts = divmod(ts,60*60)
	m,s = divmod(ts,60)
	return "%0.2d:%0.2d:%0.2d" % (h%24,m,s)

time = "00:20:30" # HH:MM:SS
newtime = add_seconds(time,4)
print time,newtime

-Drew

I have a string with a time stamp:

time = "00:20:30" # HH:MM:SS

How to add 4 seconds to this string? Thanks a lot!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...