如何修复多种错误格式的时间字符串并转换为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)
最终处理结果
| ID | Time |
|---|---|
| 190 | 01:00 |
| 213 | 17:00 |
| 228 | 02:00 |
| 279 | 09:00 |
| 1462 | 16:50 |
| 2599 | 09:00 |
| 3390 | 14:30 |
| 4838 | 09:40 |
| 1710 | 12:20 |
| 2222 | 11:14:20 |
内容的提问来源于stack exchange,提问作者alli
相关产品推荐
相关产品推荐

