将变量字符串转换为时间对象
Convert variable string to time object
我正在使用 youtube-dl
(子流程),它给出的视频时长如下:
- 如果它是 00:00:08,它给出:
8
.
- 00:03:42 >
3:42
.
- 00:03:08 >
3:08
.
- 01:02:06 >
1:02:06
.
我想将 code
格式转换为 粗体 !
试过这个但它给出了错误:
dt.strptime(YT_Duration_str, "%H:%M:%S")
ValueError: time data '8' does not match format '%H:%M:%S'
我怎样才能做到这一点?
也许试试这个?
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")
你也可以通过减去得到一个timedelta
对象:
delta = d - dt.strptime("0", "%S")
像这样提取组件:
*rest, hours, minutes, seconds = [0, 0, *map(int, YT_Duration_str.split(':'))]
然后创建一个timedelta对象:
>>> 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)
... 或一些任意日期时间
>>> 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'
我正在使用 youtube-dl
(子流程),它给出的视频时长如下:
- 如果它是 00:00:08,它给出:
8
. - 00:03:42 >
3:42
. - 00:03:08 >
3:08
. - 01:02:06 >
1:02:06
.
我想将 code
格式转换为 粗体 !
试过这个但它给出了错误:
dt.strptime(YT_Duration_str, "%H:%M:%S")
ValueError: time data '8' does not match format '%H:%M:%S'
我怎样才能做到这一点?
也许试试这个?
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")
你也可以通过减去得到一个timedelta
对象:
delta = d - dt.strptime("0", "%S")
像这样提取组件:
*rest, hours, minutes, seconds = [0, 0, *map(int, YT_Duration_str.split(':'))]
然后创建一个timedelta对象:
>>> 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)
... 或一些任意日期时间
>>> 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'