python - strptime 将字符串时间转换为时间
问题描述
我尝试将这样的严格时间转换1:34.21
为时间。我用它datetime.strptime('1:34.21', '%-H:%M.%S').time()
来进行转换,但我提出了这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 341, in _strptime
raise ValueError("'%s' is a bad directive in format '%s'" %
ValueError: '-' is a bad directive in format '%-H:%M.%S'
解决方案
只需更改'%-H:%M.%S'
为'%H:%M.%S'
from datetime import datetime
s = '1:34.21'
print(datetime.strptime(s, '%H:%M.%S').time())
输出:
01:34:21
推荐阅读
- azure-functions - 图形 API 挂钩到 Azure 函数
- go - GO中日志文件的文本解析
- amazon-route53 - 多个 SPF 记录可能会导致投递和垃圾邮件分类问题 Route53 和 G-Suite
- java - 如何使用 apache camel 在 xml 中生成自定义标签名称和命名空间
- angular - 我应该选择什么事件(更改、keyup 等)以最佳方式使用输入文本过滤数组中的数据
- spring - Spring Boot 混沌猴
- xaml - 如何在不使用绝对位置的情况下正确定位 XAML 中的元素?
- r - MuMin 中的 dredge() 函数错误
- angular - 无法读取未定义的属性“创建”
- testing - 如何使用 TestCafe 向上和向下滚动?