0

I am facing a problem with converting seconds.milliseconds into hh:mm:ss,mmm format in python. Please refer to my code below.

with open('SubRip.srt','r',encoding='UTF-8') as f:

     json_data=json.load(f)
def ss2HMS(a):
   for i in json_data:
      import time
      
      var= float(a)
   return time.strftime('%H:%M:%S.%f',time.gmtime(var))

I am trying to fetch startTime from a SRT file( which I converted into a json file) and now again that I want to make its time into SRT format, I am just trying it to make into hh:mm:ss,mmm format. The startTime in json is in seconds.millisecond format. I was able to get hh:mm:ss but not hh:mm:ss,mmm. milliseconds is not getting added. Does anybody have any idea about this?

Any help is appreciated.

Thanks for reading.

sauron_08
  • 37
  • 1
  • 8

1 Answers1

0

It seems that time.gmtime has no attribute for milliseconds. You can get the milliseconds from e.g. 161.1 seconds by taking the fractional part of the number and concatenating it to the output as follows.

>>> var = 161.1
>>> millisecs = str(var).split('.')[1][:3]
>>> millisecs
'1'
>>> time.strftime('%H:%M:%S.',time.gmtime(t)) + millisecs + '0' * (3-len(millisecs))
'00:02:41.100'
bwdm
  • 793
  • 7
  • 17
  • Thanks for answering. But there is one problem. The video's length is 2 minute and 45 seconds, but still it is showing 05:32:41.10000. I don't know why it is adding 5 hours and 30 minutes. Have you faced any similar issue like this? – sauron_08 Sep 03 '21 at 16:15
  • @ShikharJaiswal That reminds me of [timezone issues](https://stackoverflow.com/questions/4530069/how-do-i-get-a-value-of-datetime-today-in-python-that-is-timezone-aware), but I guess the 30 minutes wouldn't make sense in this case. What is the input value and the desired output? – bwdm Sep 03 '21 at 17:46
  • For example:- input value is 161.1 so the output should be 00:02:41,000. This is not precise, I am just giving an idea of how the output should look like. If you have seen a subtitle file, exactly same like that. – sauron_08 Sep 03 '21 at 17:58
  • I have again edited the code, kindly look at it again. – sauron_08 Sep 03 '21 at 18:20
  • I got the desired answer. The only problem now is that it is not coming in HH:MM:SS,Ms format. It is coming in H:MM:SS,Ms. One zero is missing from the beginning. The code that worked is below: import datetime def convert(n): return str(datetime.timedelta(seconds = n)) # Driver program n = 12345 print(convert(n)) – sauron_08 Sep 03 '21 at 19:28