如何更改 Pandas 中的日期时间格式

新手上路,请多包涵

我的数据框有一个 DOB 列(示例格式 1/1/2016 )默认情况下会转换为 Pandas dtype ‘object’。

Converting this to date format with df['DOB'] = pd.to_datetime(df['DOB']) , the date gets converted to: 2016-01-26 and its dtype is: datetime64[ns] .

现在我想将此日期格式转换为 01/26/2016 或任何其他通用日期格式。我该怎么做?

(无论我尝试什么方法,它总是以 2016-01-26 格式显示日期。)

原文由 yome 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 709
2 个回答

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object ( string )):

 import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

原文由 jezrael 发布,翻译遵循 CC BY-SA 4.0 许可协议

更改格式但不更改类型:

 df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

原文由 Yanni Cao 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题