AMM
AMM

Reputation: 196

Milliseconds to HH:MM:SS time format

I'm trying to add the timestamp of a video frame to its own frame name like "frame2 00:00:01:05", using CAP_PROP_POS_MSEC I'm getting the current position of the video file in milliseconds, what I want is to change those milliseconds to the time format "00:00:00:00:".

My code currently assigns the name like: "frame2 1.05" but ideally I would have the name like: "frame2 00:00:01:05".

Is there a library that can help me achieve this milliseconds to HH:MM:SS conversion?

import cv2
vidcap = cv2.VideoCapture('video.mp4')
success,frame = vidcap.read()
cont = 0
while success:
  frame_timestamp = (vidcap.get(cv2.CAP_PROP_POS_MSEC))/(1000)
  cv2.imwrite(f'frame{cont} '+str((format(frame_timestamp,'.2f')))+'.jpg',frame)
  success,frame = vidcap.read()
  cont+=1

Thanks!

Upvotes: 4

Views: 2322

Answers (1)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15403

Just use divmod. It does a division and modulo at the same time. It's more convenient than doing that separately.

seconds = 1.05 # or whatever

(hours, seconds) = divmod(seconds, 3600)
(minutes, seconds) = divmod(seconds, 60)

formatted = f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}"

# >>> formatted
# '00:00:01.05'

And if you need the fraction of seconds to be separated by :, which nobody will understand, you can use (seconds, fraction) = divmod(seconds, 1) and multiply fraction * 100 to get hundredth of a second.

Upvotes: 6

Related Questions