python - 转换为日期时间,假设日期的一部分可能会丢失
问题描述
假设我有一个简单的两行 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.
解决方案
您可以简单地让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 小时时钟。此外,假定月份首先出现(第二天)。
推荐阅读
- batch-file - 使用批处理在目录下查找大小为 0 的特定文件夹
- cloud - 为 OCI 上的通用 Windows Server 实例生成密码
- karate - Karate Gatling - How to run Gatling tests using Maven uber jar
- reactjs - issue while running test @types/testing-library__react/node_modules/pretty-format/build/index.d.ts (7, 13): '=' expected
- java - Oracle Database performance issue in spring-boot application
- c# - C# EF Core: How to map One-to-Zero with multiple properties (with Attributes only) [With Workaround]?
- android - BLE response back to Peripheral Connection mobile to mobile
- javascript - How do I use standalone Header in react-navigation with react-native?
- java - Spring Boot 的 JPA Native Query 中未设置参数
- python - PyQt5 无法添加标签以从线程滚动区域