Search code examples
python-3.xdatetimetimestamppython-3.7

How to easily create a datetime object from time with unit since epoch?


let's say I got a timestamp since epoch in microseconds 1611590898133828 how could I convert this easily into a datetime object considering the unit microseconds.

from datetime import datetime
timestamp_micro = 1611590898133828
dt = datetime.datetime.fromtimestamp(timestamp_micro / 1e6)

I would like to be able to do easy conversions since sometimes I have microseconds, sometimes seconds, sometimes nanoseconds to convert.

timestamp_micro = 1611590898133828
dt = datetime.datetime.fromtimestamp(timestamp_micro, unit="us")

Is this somehow possible? For me using python's datetime package is just one pain. Maybe you can also recommend another package in which timestamp handling is easier?


Solution

  • pandas.to_datetime provides the option to set the unit as a keyword:

    import pandas as pd
    
    t, UNIT = 1611590898133828, 'us'
    
    dt = pd.to_datetime(t, unit=UNIT)
    
    print(dt, repr(dt))
    # 2021-01-25 16:08:18.133828 Timestamp('2021-01-25 16:08:18.133828')
    

    You can now work with pandas' timestamps or convert to a regular Python datetime object like

    dt.to_pydatetime()
    # datetime.datetime(2021, 1, 25, 16, 8, 18, 133828)
    

    Please also note that if you use fromtimestamp without setting a time zone, you'll get naive datetime, which will be treated as local time by Python (UTC offset might not be 0). See e.g. here.