Python: How to convert string time to decimal seconds?

Viewed 111
String Time 
00:51:21,920

Decimal Time
3,081.92 (second)

Is there anyway that can convert between string time and decimal time in seconds? I want to use it in moviepy VideoFileClip.subclip.

Below is what I have done and it works. But I assume there should be an easier way like a function in a library.

def TrsTime(VideoTime):
  return (datetime.strptime(VideoTime, '%H:%M:%S,%f').hour*60*60+
  datetime.strptime(VideoTime, '%H:%M:%S,%f').minute*60+
  datetime.strptime(VideoTime, '%H:%M:%S,%f').second+
  datetime.strptime(VideoTime, '%H:%M:%S,%f').microsecond/1000/1000)
1 Answers

Yes, there is a simpler way:

from datetime import datetime as dt

(dt.strptime(VideoTime, '%H:%M:%S,%f') - dt(1900, 1, 1)).total_seconds()

>>> 3081.92

This works on the principal that the timedelta object has a .total_seconds() function. So by subtracting your time (whose year, month, day defaults to 1 Jan 1900) from 1 Jan 1900, you get the delta in seconds.

Related