Search code examples
pythonpandasdatetimetimezoneunix-timestamp

Convert time zone date column to timestamp format


I have column containing dates in format as seen here....

2021-09-02 06:00:10.474000+00:00

However, I need to convert this column into a 13 numbered timestamp.

I have tried...

df['date_timestamp'] = df[['date']].apply(lambda x: x[0].timestamp(), axis=1).astype(int)

...but this is not producing a 13 numbered timestamp, just 10 numbers instead.

How can get it to spit a 13 numbered timestamp?


Solution

  • you parse to datetime, take the int64 representation and divide that by 1e6 to get Unix time in milliseconds since the epoch (1970-01-01 UTC). Ex:

    import numpy as np
    import pandas as pd
    
    # string to datetime
    s = pd.to_datetime(["2021-09-02 06:00:10.474000+00:00"])
    
    # datetime to Unix time in milliseconds
    unix = s.view(np.int64)/1e6
    
    print(unix[0])
    # 1630562410473.9998
    

    The standard int64 representation is nanoseconds; so divide by 1e3 if you need microseconds.