【问题标题】:.dt.strftime gives back the wrong dates Pandas.dt.strftime 返回错误的日期 Pandas
【发布时间】:2024-04-27 03:10:02
【问题描述】:

我有一个带有 CreatedDate 列的 pandas 数据框。目前该列的值如下所示:

id      CreatedDate
123     1586362930000
124     1586555550000

期望的输出是:

id      CreatedDate
123     2020-04-08T15:50:00Z
124     2020-04-08T15:45:00Z

我尝试了以下方法:

# Change the column type from int to datetime64[ns]
df['CreatedDate'] = pd.to_datetime(df['CreatedDate'])

new_df = df['CreatedDate'].dt.strftime("%Y-%m-%d"+"T"+"%H:%M:%S"+"Z")

输出是这样的:

id      CreatedDate
123     1970-01-01 00:26:26.362930
124     1970-01-01 00:26:26.365487

这出乎我的意料,我知道那几天应该是 4 月 8 日。 我只用一个字符串测试了dt.strftime("%Y-%m-%d"+"T"+"%H:%M:%S"+"Z"),它返回了所需的输出,但是,当我将它应用到数据帧时,它不能正常工作

【问题讨论】:

    标签: python pandas date datetime strftime


    【解决方案1】:

    这是unix时间

    pd.to_datetime(df.CreatedDate,unit='ms').dt.strftime("%Y-%m-%d""T""%H:%M:%S""Z")
    
    0    2020-04-08T16:22:10Z
    1    2020-04-10T21:52:30Z
    Name: CreatedDate, dtype: object
    

    【讨论】:

    • 谢谢@YOBEN_S 这正是我所需要的!