Search code examples
pythonpython-3.xtimetimedeltayoutube-dl

Convert variable string to time object


I'm working with youtube-dl (subprocess), it gives the video duration like this:

  • if it's 00:00:08, it gives: 8.
  • 00:03:42 > 3:42.
  • 00:03:08 > 3:08.
  • 01:02:06 > 1:02:06.

I want to convert the code formats to the bold!
Tried this but it gives error:

dt.strptime(YT_Duration_str, "%H:%M:%S")

ValueError: time data '8' does not match format '%H:%M:%S'

how can I achieve that?


Solution

  • Maybe try this?

    n_colons = YT_Duration_str.count(":")
    
    if n_colons == 0:
        d = dt.strptime(YT_Duration_str, "%S")
    elif n_colons == 1:
        d = dt.strptime(YT_Duration_str, "%M:%S")
    elif n_colons == 2:
        d = dt.strptime(YT_Duration_str, "%H:%M:%S")
    
    d.strftime("%H:%M:%S")
    

    You can also get a timedelta object by subtracting:

    delta = d - dt.strptime("0", "%S")