Search code examples
pythonpandasdatetimetimestampunix-timestamp

Python: convert timestamp to datetime


I have the following dataframe:

df=pd.DataFrame(index=[0])
df['timestamp'] = 1642104862000
df:
    timestamp
0   1642104862000

I am applying the following code:

df['timestamp'] = pd.to_datetime(df['timestamp'], infer_datetime_format=True)

But the date I am getting is 1970-01-01 00:27:22.104862 which is wrong. The right date is 2022-01-13 20:14:22.

How can I get the right date? Thank you


Solution

  • Make sure you're using the right unit. Try this code:

    df['timestamp'] = pd.to_datetime(df['timestamp'], infer_datetime_format=True, unit="ms")