You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python convert_datetime函数报错求助:时间字符串转datetime对象失败

解决datetime字符串转换问题

你的代码存在三个关键问题,修正后即可正常工作:

  1. 格式字符串错误:datetime.strptime不支持yyyy-mm-dd HH:MM:SS这种写法,必须使用Python标准的%开头格式占位符,对应正确格式为%Y-%m-%d %H:%M:%S:

    • %Y:4位数字年份
    • %m:2位数字月份
    • %d:2位数字日期
    • %H:24小时制小时数
    • %M:分钟数
    • %S:秒数
  2. 缺少返回语句:函数没有返回转换后的datetime对象,需要添加return关键字。

  3. 未导入datetime模块:如果代码所在作用域没有导入datetime模块,必须先导入。

修正后的完整代码:

import datetime

def convert_datetime(datetime_str):
    return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")

测试示例:

# 调用函数
result = convert_datetime("2024-06-15 09:45:30")
print(result)  # 输出:2024-06-15 09:45:30
print(type(result))  # 输出:<class 'datetime.datetime'>

内容的提问来源于stack exchange,提问作者Astrid M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 17:32:40