pandas 将数据框列中的日期转换为 MM/DD/YYYY

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36589020/
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 01:02:32  来源:igfitidea点击:

Conversion of dates in the dataframe column into MM/DD/YYYY

pythondatepandasdataframe

提问by User1090

I have 4 dataframes named df1,df2,df3,df4with one column Date. The column consist of dates with different format. df1has date column of type int64, df2has date column of type object, df3has date column has type object, df4has date column of type object. Below are the dataframe and its data.

我有 4 个名为df1, df2, 的数据框df3df4其中有一列Date。该列由不同格式的日期组成。df1具有类型为 int64 的df2日期列,具有类型为对象的df3日期列,具有类型为对象的日期列,具有类型为对象的df4日期列。以下是数据框及其数据。

df1:
          Date
0     20160301
1     20160301
2     20160301
3     20160301

df2: 
      Date
0   01/03/2016
1   01/03/2016
2   01/03/2016

df3:
      Date
0   31-Mar-16
1   31-Mar-16
2   31-Mar-16

df4:
      Date
0  25/02/2016
1  25/02/2016
2  25/02/2016

I want to convert these dates in the form as mm/dd/yyyyof type date. Can anyone help me on this?

我想以mm/dd/yyyytype的形式转换这些日期date。谁可以帮我这个事?

回答by jezrael

I think you can use to_datetimeand dt.strftime, but typeis not datetime, but string:

我认为您可以使用to_datetimeand dt.strftime,但type不是datetime,但是string

df1['Date'] = pd.to_datetime(df1['Date'], format='%Y%m%d').dt.strftime('%m/%d/%Y')
df2['Date'] = pd.to_datetime(df2['Date']).dt.strftime('%m/%d/%Y')
df3['Date'] = pd.to_datetime(df3['Date']).dt.strftime('%m/%d/%Y')
df4['Date'] = pd.to_datetime(df4['Date']).dt.strftime('%m/%d/%Y')

print df1
print df2
print df3
print df4
         Date
0  03/01/2016
1  03/01/2016
2  03/01/2016
3  03/01/2016
         Date
0  01/03/2016
1  01/03/2016
2  01/03/2016
         Date
0  03/31/2016
1  03/31/2016
2  03/31/2016
         Date
0  02/25/2016
1  02/25/2016
2  02/25/2016

print type(df1.at[0,'Date'])
<type 'str'>

If you want datetime, format is YY-MM-DD:

如果需要datetime,格式为YY-MM-DD

df1['Date'] = pd.to_datetime(df1['Date'], format='%Y%m%d')
df2['Date'] = pd.to_datetime(df2['Date'])
df3['Date'] = pd.to_datetime(df3['Date'])
df4['Date'] = pd.to_datetime(df4['Date'])

print df1
print df2
print df3
print df4
        Date
0 2016-03-01
1 2016-03-01
2 2016-03-01
3 2016-03-01
        Date
0 2016-01-03
1 2016-01-03
2 2016-01-03
        Date
0 2016-03-31
1 2016-03-31
2 2016-03-31
        Date
0 2016-02-25
1 2016-02-25
2 2016-02-25

print type(df1.at[0,'Date'])
<class 'pandas.tslib.Timestamp'>

More info about formating datetimeis here.

有关格式化更多信息datetime在这里