Home > Net >  Python set value with loop and if
Python set value with loop and if

Time:09-22

I have a date and time column which I set using pd.to_datetime but panda reads the date wrong when the first value is not a 0. Example is 5/08/2021 when it needs to be 05/08/2021. If the date is 10/08/2021 it reads it fine.

Can you please help with a python loop style code which looks at each date per row and if there is a / as the second value then add a 0 at the front of the date. If the second value is not a / then skip to the next row.

I want to use this code when the column is in object format. Then when the column is edited I will do the pd.to_datetime.

Thanks if you can help.

CodePudding user response:

>>> pd.to_datetime('5/08/2021', format='%d/%m/%Y')
Timestamp('2021-08-05 00:00:00')

No need to any loop. This works fine. You just need to define the time format as '%d/%m/%Y'.

  • Related