Conversion of dates in the dataframe column into MM/DD/YYYY
13,136
I think you can use to_datetime
and dt.strftime
, but type
is not datetime
, but 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
:
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 datetime
is here.
Author by
User1090
Updated on June 12, 2022Comments
-
User1090 about 2 years
I have 4 dataframes named
df1
,df2
,df3
,df4
with one columnDate
. The column consist of dates with different format.df1
has date column of type int64,df2
has date column of type object,df3
has date column has type object,df4
has date column of type object. Below are the dataframe and its data.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/yyyy
of typedate
. Can anyone help me on this? -
jezrael about 8 yearsI think in
df1
anddf2
is unclear, if first are days or months in string. Is correct my solution ?