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

如何在Pandas中将yyyy-dd-mm格式Timestamp转换为yyyy-mm-dd并生成客户月份

解决方法

问题核心是你的Timestamp列实际为yyyy-dd-mm格式,但Pandas默认按yyyy-mm-dd规则解析,导致月份和日期被颠倒,最终生成的Customer_month列结果错误。

步骤1:重新正确解析Timestamp列

  • 如果Timestamp是字符串类型,直接转换为datetime时指定原格式:
    import pandas as pd
    # 转换字符串为正确的datetime格式
    data['Timestamp'] = pd.to_datetime(data['Timestamp'], format='%Y-%d-%m %H:%M:%S')
    
  • 如果Timestamp已被错误解析为datetime类型,先转成字符串再重新解析:
    data['Timestamp'] = pd.to_datetime(data['Timestamp'].astype(str), format='%Y-%d-%m %H:%M:%S')
    

步骤2:生成正确的Customer_month列

解析完成后,再生成当月第一天的日期列:

data['Customer_month'] = data['Timestamp'].dt.strftime('%Y-%m-01')

若希望Customer_month保持datetime类型(而非字符串),可改用:

data['Customer_month'] = data['Timestamp'].dt.to_period('M').dt.start_time

验证结果

执行后你的DataFrame会符合预期:

Timestamp           Name            Customer_month
2022-11-05 21:31:16 Deepak Kumar    2022-11-01
2022-11-05 21:44:55 Subhash chandra 2022-11-01

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:15:40