python - 数据集识别12 :00AM as 00:00AM

标签 python python-3.x datetime

我从 Python 收到以下错误:

ValueError: time data '05/10/2015 00:19:49 AM' does not match format '%d/%m/%Y %I:%M:%S %p'

我认为造成这种情况的原因是数据集与datetime库识别午夜12点时间的方式略有不一致。我认为可能需要通过将 00 更改为 12 来纠正。

例如以下数据显示如下:

05/10/2015 12:59:12 PM

数据未使用 24 小时制。有没有人有办法解决这个问题?

最佳答案

一个简单的尝试怎么样 - 除了,先尝试%I,然后使用%H,如果你得到ValueError:

date_string = '05/10/2015 00:19:49 AM'
try:
    date = time.strptime(date_string, '%d/%m/%Y %I:%M:%S %p')
except ValueError:
    date = time.strptime(date_string, '%d/%m/%Y %H:%M:%S %p')

print(time.strftime('%d/%m/%Y %H:%M:%S %p', date))

输出:

05/10/2015 00:19:49 AM

%I 应该适用于所有 12 小时格式的日期,除了 00 表示小时的日期。对于这些情况,使用 %H 的 24 小时格式应该可以正常工作。

日期时间的工作方式相同:

import datetime

date_string = '05/10/2015 00:19:49 AM'
try:
    date = datetime.datetime.strptime(date_string, '%d/%m/%Y %I:%M:%S %p')
except ValueError:
    date = datetime.datetime.strptime(date_string, '%d/%m/%Y %H:%M:%S %p')

print(date.strftime('%d/%m/%Y %H:%M:%S %p'))

输出:

05/10/2015 00:19:49 AM

关于python - 数据集识别12 :00AM as 00:00AM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37098111/

相关文章:

python - 如何在Tornado中设置静态路径?

python - 如何将字符串转换为所需的形式?

python - 如何获取 pandas 数据框的字符串列表?

mysql - CakePHP 将日期时间转换为日期并对结果进行分组

python - 在 sqlite3 WHERE 列 = 中插入或替换

python - 结构错误 : unpack requires a string argument of length 16

python-3.x - 使用整数输入的曲线拟合 Python 3.3

python - 在网络服务器上运行的 Flask 应用程序调用远程服务器 python 模块

datetime - Flutter:DateTime.now 不反射(reflect)手动设置的时区

c# - 原始 UTC 值的 Postgres 时间戳和时区