Search code examples
pythonstringdatetimetimedelta

how to convert datetime-like string into milliseconds


I have a user-defined function (return_times) that takes json file and returns two datetime-like strings.

time_1, time_2= return_times("file.json")
print(time_1, time_2) # outputs: 00:00:11.352 00:01:51.936

By datetime-like string I mean 00:00:11.352 which suits '%H:%M:%S.%f' formatting. However, when I try to convert them into milliseconds, I get negative values.

from datetime import datetime

dt_obj_1 = datetime.strptime(time_1, '%H:%M:%S.%f')
start_ms = dt_obj_1.timestamp() * 1000

dt_obj_2 = datetime.strptime(time_2, '%H:%M:%S.%f')
end_ms = dt_obj_2.timestamp() * 1000

print(start_ms, end_ms ) # outputs: -2209019260648.0 -2209019160064.0

If I success I would like to trim a video with the following command:

from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
ffmpeg_extract_subclip("long_video.mp4", start_ms, end_ms, targetname="video_trimmed.mp4"), so just delete ` * 1000` part. 

Note that ffmpeg_extract_subclip requires its t1 and t2 parameters to be in seconds, not in milliseconds as I initially thought.

Because of those negative integers I am not able to successfully run the trimming process. I searched the web that mainly discusses several formats for the year, month and day, but not '%H:%M:%S.%f'.

What may I be overlooking?


Solution

  • What may I be overlooking?

    time.strptime docs

    The default values used to fill in any missing data when more accurate values cannot be inferred are (1900, 1, 1, 0, 0, 0, 0, 1, -1).

    whilst start of epoch is 1970. You might get what you want by computing delta between what you parsed and default strptime as follows:

    import datetime
    time1 = "00:00:11.352"
    delta = datetime.datetime.strptime(time1, "%H:%M:%S.%f") - datetime.datetime.strptime("", "")
    time_s = delta.total_seconds()
    print(time_s)
    

    output

    11.352