0

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?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
user7638008
  • 137
  • 9

2 Answers2

1

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

You can create new javascript date objects by simply calling const dt = new Date(timestamp). The timestamp value here is an epoch up to milliseconds precision. JavaScript does have native support for higher precision.

If you constantly need to work with dates, I would recommend you to use a package such as momentJS, since native JS is quite a pain to handle dates/times.

Murilo Schünke
  • 106
  • 2
  • 7