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

如何将df['time']列的2022-11-27T23:40:26格式转为%Y-%m-%d %H:%M:%S

解决DataFrame时间列格式转换问题

针对你DataFrame中df['time']列的2022-11-27T23:40:26格式转成%Y-%m-%d %H:%M:%S的需求,这里有几种实用方案:

  • 方案一:自动解析+格式化(推荐)
    利用pandas的pd.to_datetime自动识别ISO时间格式,再通过dt.strftime指定输出格式:

    import pandas as pd
    
    # 转换并格式化时间列
    df['time'] = pd.to_datetime(df['time']).dt.strftime('%Y-%m-%d %H:%M:%S')
    

    这种方法兼容性强,即便列中存在少量格式不一致的时间,pd.to_datetime也能尝试自动解析(可配合errors='coerce'参数处理异常值)。

  • 方案二:字符串替换(简单直接)
    如果你确认所有时间字符串都严格是YYYY-MM-DDTHH:MM:SS格式,直接替换T为空格即可:

    # 仅替换字符得到字符串格式
    df['time'] = df['time'].str.replace('T', ' ')
    
    # 若需要转为datetime类型便于后续时间操作
    df['time'] = pd.to_datetime(df['time'].str.replace('T', ' '))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:35:31