Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an H:MM:SS time string to seconds in Python?

Tags:

python

Basically I have the inverse of this problem: Python Time Seconds to h:m:s

I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I need the integer number of seconds that it represents. How can I do this in python?

For example:

  • "1:23:45" would produce an output of 5025
  • "0:04:15" would produce an output of 255
  • "0:00:25" would produce an output of 25

etc

like image 926
hughes Avatar asked Jun 19 '11 14:06

hughes


People also ask

How do I convert time to seconds in Python?

Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch. Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds.

How do I convert hours minutes seconds to time in Python?

The time module of Python provides datetime. strftime() function to convert seconds into hours, minutes, and seconds. It takes time format and time. gmtime() function as arguments.


1 Answers

def get_sec(time_str):     """Get seconds from time."""     h, m, s = time_str.split(':')     return int(h) * 3600 + int(m) * 60 + int(s)   print(get_sec('1:23:45')) print(get_sec('0:04:15')) print(get_sec('0:00:25')) 
like image 198
taskinoor Avatar answered Oct 11 '22 04:10

taskinoor