pythondataframedatepycharm

Python change a date format in dataframe


I have a dataset containing a column "date":

date                     item
20.3.2010 17:08           a 
20.3.2010 11:16           b
2010-03-20 15:55:14.060   c
2010-03-21 13:56:45.077   d

I would like to convert all values that have format as 20.3.2010 17:08 into 2010-03-21 13:56:45.077.

Does anybody have an idea?

Thank you.


Solution

  • Check on below:

    from datetime import datetime
    
    INPUT_FORMAT = '%d.%m.%Y %H:%M'
    OUTPUT_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
    
    datetime.strptime('20.3.2010 17:08',INPUT_FORMAT).strftime(OUTPUT_FORMAT)
    #Output '2010-03-20 17:08:00.000000'
    

    You could find more information in offcial strptime and strftime.

    To do a 100% match with 3 digits microseconds you could use this SO approach.