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

如何修复多种错误格式的时间字符串并转换为datetime格式?

批量清洗异常时间格式方案

针对你遇到的多种异常时间格式,可通过正则表达式+Pandas字符串操作批量处理,覆盖所有场景:

处理步骤及代码

首先构造测试数据(可替换为你的DataFrame):

import pandas as pd

data = {
    'ID': [190, 213, 228, 279, 1462, 2599, 3390, 4838, 1710, 2222],
    'Time': ['c: 1:00', 'c:17:00', 'c: 2:00', 'c:09:00', 'c16:50', 'c:09:00', 'c14:30', 'c: 9:40', "12'20", '1114:20']
}
df = pd.DataFrame(data)

1. 移除开头的冗余标识(c/ c:/ c加空格)

用正则匹配开头的c、可选冒号及空格,直接替换为空:

df['Time'] = df['Time'].str.replace(r'^c:?\s?', '', regex=True)

2. 替换非标准分隔符

将单引号替换为标准冒号:

df['Time'] = df['Time'].str.replace(r"'", ':', regex=False)

3. 修复四位数字开头的格式

针对1114:20这类错误格式,拆分出小时、分钟、秒:

df['Time'] = df['Time'].str.replace(r'^(\d{2})(\d{2}):(\d{2})$', r'\1:\2:\3', regex=True)

4. 可选:统一时分格式(补零)

给单个数字的小时补前导零,让格式更规范:

df['Time'] = df['Time'].str.replace(r'^(\d):', r'0\1:', regex=True)

最终处理结果

IDTime
19001:00
21317:00
22802:00
27909:00
146216:50
259909:00
339014:30
483809:40
171012:20
222211:14:20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:55:31