Home > Software design >  Convert variable string to time object
Convert variable string to time object

Time:02-02

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?

CodePudding user response:

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")

CodePudding user response:

Extract the components like this:

*rest, hours, minutes, seconds = [0, 0, *map(int, YT_Duration_str.split(':'))]

Then create a timedelta object:

>>> YT_Duration_str = '01:02:03'
>>> *rest, hours, minutes, seconds = [0, 0, *map(int, YT_Duration_str.split(':'))]
>>> td = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
>>> td
datetime.timedelta(seconds=3723)

... or some arbitrary datetime

>>> dt = datetime.datetime.now().replace(hour=hours, minute=minutes, second=seconds, microsecond=0)
>>> dt
datetime.datetime(2022, 2, 2, 1, 2, 3)
>>> dt.strftime('%H:%M:%S')
'01:02:03'
  •  Tags:  
  • Related