In Pandas, how to convert a string to a datetime object with milliseconds?

18,102

Solution 1

Something like this should work

pd.to_datetime('2016-06-10 18:57:35:317', format="%Y-%m-%d %H:%M:%S:%f")

You can look up datetime formats here

Solution 2

Normally there is a period / full-stop between the seconds and microseconds.

Since your data does not have that you can specify how your data is formatted:

pd.to_datetime('2016-06-10 18:57:35:317', format='%Y-%m-%d %H:%M:%S:%f')
Share:
18,102
bananana
Author by

bananana

Updated on July 28, 2022

Comments

  • bananana
    bananana almost 2 years

    I have a column of event's timestamp in my dataframe, looks like "2016-06-10 18:58:25:675", the last 3 digits are milliseconds, is there a efficient way to transform this column to a Pandas datatime type?

    When I try:

    pd.to_datetime('2016-06-10 18:57:35:317')
    

    An error occurs saying "Unknown string format".

  • mechanical_meat
    mechanical_meat almost 8 years
    Awesome! We answered at the same time! Well played, Sir
  • mgilbert
    mgilbert almost 8 years
    Millisecond resolution ;)
  • Andreas Gebhard
    Andreas Gebhard almost 2 years
    This should be an example in the docs!