23

I have a dataframe (df) that has a date column (column name : sale_date) that stores data in the below format

dd/mm/yy hh:mm:ss

I am trying to convert it to yyyy-mm-dd hh:mm:ss. Tried with the below but however it still does not convert it to the required format.

df['sale_date'] = pd.to_datetime(df['sale_date'])

Could anyone assist in converting the format of this date column. Thanks

Kevin Nash
  • 1,511
  • 3
  • 18
  • 37
  • `pd.to_datetime` should convert to a datetime, and you should then be able to format how you want. Why are you needing it in that specified format? You can use `dt.strftime` to convert to any format, but it converts the column to a string, not a datetime. – Ken Syme Aug 07 '18 at 10:48
  • @KenSyme, Thanks for the reply. I am trying to get a date column value returned.. – Kevin Nash Aug 07 '18 at 11:01
  • Does your `to_datetime` line not work for that? Are you getting an error? What output do you get and what are you expecting to get? – Ken Syme Aug 07 '18 at 11:04

2 Answers2

33

If you know you will have a consistent format in your column, you can pass this to to_datetime:

df['sale_date'] = pd.to_datetime(df['sale_date'], format='%d/%m/%y %H:%M:%S')

If your formats aren't necessarily consistent but do have day before month in each case, it may be enough to use dayfirst=True though this is difficult to say without seeing the data:

df['sale_date'] = pd.to_datetime(df['sale_date'], dayfirst=True)
asongtoruin
  • 9,794
  • 3
  • 36
  • 47
25

You can do so:

df['sale_date'] = pd.to_datetime(df['sale_date'], format='%d/%m/%y %H:%M:%S').dt.strftime('%Y-%m-%d %H:%M:%S')

Input:

           sale_date
0  04/12/10 21:12:35
1  04/12/10 21:12:30

Output:

             sale_date
0  2010-12-04 21:12:35
1  2010-12-04 21:12:30
Joe
  • 12,057
  • 5
  • 39
  • 55