首页 > 解决方案 > 转换为日期时间,假设日期的一部分可能会丢失

问题描述

假设我有一个简单的两行 df:

|     date_column      |
|----------------------|
|10/23/2001 12:34:44 AM|
|10/23/2001 12:33:44   |
|----------------------|

如果我运行该行:

df[date_column] = pd.to_datetime(df[date_colummn], format='%m/%d/%Y %H:%M:%S')

我得到错误

'未转换的数据仍然存在'

但我对'%p'失踪完全没问题,我只想得到%m/%d/%Y.

有什么办法可以做到这一点?我可以告诉熊猫只解析我的“格式”中的当前数据并忽略其余的,如果它丢失了吗?

UDPATE

看起来像这个关键字,根据文档可能会做的伎俩:

exact: bool, True by default
Behaves as: - If True, require an exact format match. - If False, allow the format to match anywhere in the target string.

标签: pythonpandasdatetime

解决方案


您可以简单地让pandas to_datetime推断格式:

import pandas as pd

s = pd.to_datetime(["10/23/2001 12:34:44 AM", "10/23/2001 12:33:44"])

print(s)
# DatetimeIndex(['2001-10-23 00:34:44', '2001-10-23 12:33:44'], dtype='datetime64[ns]', freq=None)

请注意,如果未指定 AM/PM,则假定为 24 小时时钟。此外,假定月份首先出现(第二天)。


推荐阅读