尝试使用 datetime.strptime 将字符串转换为日期时间对象时如何修复错误?

问题描述 投票:0回答:1
date_str = "2024-04-19 15:30:00"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")

我尝试使用 Python 中的

datetime.strptime()
方法将字符串转换为日期时间对象。我期望该方法根据指定的格式解析字符串并返回一个日期时间对象。但是,我遇到了有关格式字符串的错误。

python datetime string-parsing datetime-conversion custom-error-handling
1个回答
1
投票

您的代码不完整,请提供完全可重现的代码和错误。
下面是使用strptime方法的完整Python3代码。
注意第一行,它从 datetime 模块导入 datetime 类。

from datetime import datetime

date_str = "2024-04-19 15:30:00"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(datetime_obj)
© www.soinside.com 2019 - 2024. All rights reserved.