0

I have this date column which the dtype: object and the format is 31-Mar-20. So i tried to turn it with datetime.strptime into datetime64[D] and with format of 2020-03-31 which somehow whatever i have tried it does not work, i have tried some methode from this and this. In some way, it does turn my column to datetime64 but it has timestamp in it and i don't want it. I need it to be datetime without timestamp and the format is 2020-03-31 This is my code

dates =  [datetime.datetime.strptime(ts,'%d-%b-%y').strftime('%Y-%m-%d') 
          for ts in df['date']]
df['date']= pd.DataFrame({'date': dates})
df = df.sort_values(by=['date'])
random student
  • 683
  • 1
  • 15
  • 33

2 Answers2

1

This approach might work -

import pandas as pd
df = pd.DataFrame({'dates': ['20-Mar-2020', '21-Mar-2020', '22-Mar-2020']})
df
     dates
0  20-Mar-2020
1  21-Mar-2020
2  22-Mar-2020

df['dates'] = pd.to_datetime(df['dates'], format='%d-%b-%Y').dt.date
df
    dates
0  2020-03-20
1  2020-03-21
2  2020-03-22
Sajan
  • 1,247
  • 1
  • 5
  • 13
0
df['date'] = pd.to_datetime(df['date'], format="%d-%b-%y") 

This converts it to a datetime, when you look at df it displays values as 2020-03-31 like you want, however these are all datetime objects so if you extract one value with df['date'][0] then you see Timestamp('2020-03-31 00:00:00')

if you want to convert them into a date you can do

df['date'] = [df_datetime.date() for df_datetime in df['date'] ]

There is probably a better way of doing this step.

WGP
  • 708
  • 2
  • 7
  • 18