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

Python处理CSV时间列异常:转换datetime类型失败求助

解决方案
  • 不要用Python标准库的datetime.strptime处理Pandas列(它仅支持单个字符串),改用Pandas专门的pd.to_datetime批量处理整列数据,同时注意匹配带AM/PM的时间格式:

    import pandas as pd
    
    # 读取CSV时强制该列为字符串类型,避免自动解析丢失完整时间信息
    df = pd.read_csv('你的文件路径.csv', dtype={'start': str})
    
    # 转换为datetime格式,格式字符串要匹配你的时间格式
    df['start'] = pd.to_datetime(df['start'], format='%d/%m/%Y %I:%M:%S%p')
    

    格式参数说明:

    • %d/%m/%Y:对应日/月/4位年份(比如1/1/2022)
    • %I:12小时制的小时数(适配12:34里的12)
    • %M:%S:分:秒
    • %p:匹配字符串末尾的am/pm标识
  • 转换后如果单元格仍只显示分秒毫秒,可调整Pandas的显示设置,同时保持datetime类型以便计算时间差:

    # 让列完整显示内容
    pd.set_option('display.max_colwidth', None)
    # 若需要自定义显示格式,可新增列存储字符串格式,但计算时间差时要保留原datetime列
    # df['start_display'] = df['start'].dt.strftime('%d/%m/%Y %I:%M:%S%p')
    
  • 若转换时遇格式错误,可加入errors='coerce'参数定位异常值:

    df['start'] = pd.to_datetime(df['start'], format='%d/%m/%Y %I:%M:%S%p', errors='coerce')
    # 查看转换失败的行
    print(df[df['start'].isna()])
    
  • 时间差计算:只要两列都是datetime类型,直接相减即可得到Timedelta对象:

    df['time_diff'] = df['end'] - df['start']
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:15:59