0

Please can someone help me with the correct way to convert "hh:mm:ss AM/PM" Object column to Timestamp. E.g. Input = "06:12:39 PM" Expected Output = 18:12:39

I tried the below already:

df['col'] = pd.to_datetime(df.col,format='%H:%M:%S %p').dt.time

However I am getting output = 06:12:39 with the datatype unchanged

Not sure where I am going wrong here. Thank you.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
  • does this help: https://stackoverflow.com/questions/1759455/how-can-i-account-for-period-am-pm-using-strftime? – Pygirl Jun 12 '20 at 21:12
  • I don't think that the related question (on strftime and AM/PM) answers the pandas-related question here. The answer depends on what the datatype of the pandas column is. Please update the question with the output of `df['col'].dtype`. – Han-Kwang Nienhuys Jun 12 '20 at 21:46
  • @Han-KwangNienhuys : My requirement is to have the column datatype changed to DateTime in the mentioned format. XXavier provided me with an almost solution where I can now see the required output minus the Datatype modification - but that much is enough for me to proceed. Thank you all for your help. – utkarsh sharma Jun 13 '20 at 19:24
  • @Pygirl : Yes, it helped actually. I figured out where I was going wrong. Thank you. – utkarsh sharma Jun 13 '20 at 19:26

1 Answers1

2

Can you try this

For single datetime value, tme='06:12:39 PM' pd.to_datetime(tme).strftime('%H:%M:%S') For the column you can do this. This will give you the time in string that you need to convert. pd.to_datetime(df['col']).dt.strftime('%H:%M:%S')

XXavier
  • 1,206
  • 1
  • 10
  • 14
  • Yes - this worked pretty well - Thank you. Now I have the Time in string and can easily convert this to the required timestamp datatype. – utkarsh sharma Jun 13 '20 at 19:20