Skip to main content
 首页 » 编程设计

python之来自字符串的转换时间

2024年10月25日24emanlee

我在 Python 中遇到时间转换问题: 我尝试这样做:

from datetime import datetime 
date_object = datetime.strptime('12:29:31.181', '%H:%M:%S') 

我收到一个错误:“ValueError:未转换的数据仍然存在:.181”
你能帮帮我吗?

请您参考如下方法:

您需要添加 %f微秒:

In [335]: 
 
from datetime import datetime 
date_object = datetime.strptime('12:29:31.181', '%H:%M:%S.%f') 
print(date_object) 
1900-01-01 12:29:31.181000 

您的格式字符串必须消耗传入字符串中的所有字符,如果仍有剩余则引发 ValueError。