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

Python中无法将'09-JUN-14 12.00.00.000000000 AM'转为datetime的问题

解决字符串转Datetime的格式错误问题

你之前的转换失败是因为用错了datetime和pandas的格式码,以下是两种正确的实现方式:

方法一:使用Python标准库datetime

输入字符串的结构是日-月份缩写-两位年份 12小时制时.分.秒.微秒 AM/PM,对应正确的格式码如下:

  • %d:两位数字的日期(09)
  • %b:英文月份缩写(JUN)
  • %y:两位数字的年份(14,自动转换为2014)
  • %I:12小时制的小时数(12)
  • %M:分钟(00)
  • %S:秒(00)
  • %f:微秒(支持最多6位,超过部分会被截断不影响结果)
  • %p:AM/PM标识

代码示例:

from datetime import datetime

# 若系统默认语言不是英文,需先设置英文locale(可选)
# import locale
# locale.setlocale(locale.LC_TIME, 'en_US.UTF-8')

# 转换为datetime对象
dk = datetime.strptime('09-JUN-14 12.00.00.000000000 AM', '%d-%b-%y %I.%M.%S.%f %p')
# 输出目标格式的字符串
print(dk.strftime('%Y-%m-%d %H:%M:%S'))  # 结果:2014-06-09 00:00:00

方法二:使用pandas的to_datetime

pandas的格式规则和标准库基本一致,直接用相同格式码即可:

import pandas as pd

# 转换为datetime对象
dk = pd.to_datetime('09-JUN-14 12.00.00.000000000 AM', format='%d-%b-%y %I.%M.%S.%f %p')
# 输出目标格式的字符串
print(dk.strftime('%Y-%m-%d %H:%M:%S'))  # 结果:2014-06-09 00:00:00

注意:12小时制的12 AM对应24小时制的00:00,转换后的结果符合你的预期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:15:18