Search code examples
pythonpandasstring-to-datetime

How to convert string year-dayofyear-milliseconds to datetime object


In a pandas DataFrame I have weird datetime format like so:

0    201913907050435
1    201913908520126
2    201914004163647
3    201914019315651
4    201914019320917
Name: DATETIME, dtype: object

What I know is, that it's Year followed by day of the year. I guess the number after that is the time in milliseconds or nanoseconds.

I want to transform the type to a pandas datetime object. So far I have:

pd.to_datetime(df.DATETIME, format='%Y%j%f')

which gives me:

0   2019-05-19 00:00:00.070504350
1   2019-05-19 00:00:00.085201260
2   2019-05-20 00:00:00.041636470
3   2019-05-20 00:00:00.193156510
4   2019-05-20 00:00:00.193209170
Name: DATETIME, dtype: datetime64[ns]

The problem is that HH:MM:SS is always 0 and not filled in correctly. What datetime code do I need instead of %f that can represent milliseconds (or whatever this number is)?

I could not find it in this table.

Thank you!


Solution

  • ### try this
    print(pd.to_datetime('201913907050435', format="%Y%j%H%M%S%f"))
    ##output:
    2019-05-19 07:05:04.350000