pandas 如何更改数据框中的日期格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42152066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:56:53  来源:igfitidea点击:

How to change the format of date in a dataframe?

pythonpandas

提问by user517696

I have a date column in a dataframe in the format yyyy/mm/ddlike this:

我在数据框中有一个日期列,格式yyyy/mm/dd如下:

Date
2016/08/22
2016/08/10
2016/08/08
...

How do I convert it into dd/mm/yyyyformat??

怎么转换成dd/mm/yyyy格式??

回答by Alex Fung

I assume the column is in string.

我假设该列是字符串。

import pandas as pd

df = (pd.DataFrame([['2016/08/22']*10]*10))

df[0] = pd.to_datetime(df[0]).apply(lambda x:x.strftime('%d/%m/%Y'))

output:

输出:

enter image description here

在此处输入图片说明

回答by piRSquared

Use a vectorized approached with the dtaccessor in combination with strftime

dt访问器结合使用矢量化方法strftime

df = pd.DataFrame(dict(date=['2011/11/30', '2012/03/15']))
df['date'] = pd.to_datetime(df.date).dt.strftime('%d/%m/%Y')

print(df)

         date
0  30/11/2011
1  15/03/2012

回答by Shubham R

Suppose your dataframe df has date column 'date', then you can use this method, to change your date format.

假设您的数据框 df 具有日期列“日期”,那么您可以使用此方法来更改您的日期格式。

df['date'] = df['date'].dt.strftime('%m/%d/%Y')