Home > Blockchain >  Converting A timestamp string to the right format
Converting A timestamp string to the right format

Time:01-04

I have a datafield, in the format : '13:55:07 03-01-2023' This is 3rd of january and not 1st of March

I want to convert this into a timestamp, when I do it directly using pd.to_datetime(order_data['exch_tm']) I get the output of the timestamp like this : Timestamp('2023-03-01 13:55:07')

However, this is incorrect as it converting into 1st of march, whereas it should convert it into 3rd of January.

CodePudding user response:

Is the datetime format always the same in the data? If so, what about using a format parameter to pd.to_datetime:

>>> import pandas as pd
>>> pd.to_datetime('13:55:07 03-01-2023', format='%H:%M:%S %d-%m-%Y')
Timestamp('2023-01-03 13:55:07')

CodePudding user response:

You just need to mention the format of date entered.

For eg:

pd.to_datetime(order_data['exch_tm'],format='%H:%M:%S %d-%m-%Y'))

modify it as per your needs and you can find more about datetime is here.

CodePudding user response:

If you want the day to appear before the month in the date string, you can tell the pd.to datetime function to accept the dayfirst=True option. The function will correctly understand the date as a result.

For more information refer doc

  • Related