Pandas:将日期时间 (%Y-%d-%m %H:%M) 转换为 (%Y-%m-%d %H:%M)

ana*_*ine 3 python dataframe pandas

我一直在用例子等来讨论这个主题,但我似乎无法让它发挥作用。

我有一个 pandas 数据框,其中有一个名为“Date我希望将格式从年-月-日小时:分钟更改为年-月-日小时:分钟”的字段。新的领域将是Date2. 该Date字段的类型被报告为“对象”。

到目前为止,我已经尝试过以下几种变体:

df['Date2'] = pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M').dt.strftime('%Y-%d-%m %H:%M')

df['Date2'] = pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M')
Run Code Online (Sandbox Code Playgroud)

该字段中的示例日期Date2020-02-12 04:00
所需的Date2输出是2020-12-02 04:00

mhh*_*bib 5

我在 Google Colab 中完成并练习了整个过程。要获取所有源代码,请找到我的要点

df['Date2']=pd.to_datetime(df["Date"]).dt.strftime("%Y-%m-%d %H:%M")
Run Code Online (Sandbox Code Playgroud)