0

Why can I not convert the following timestamp?

from datetime import date

timestamp = date.fromtimestamp(1571266800000000000)
print("Date =", timestamp)

https://www.epochconverter.com/ gives the right result.

martineau
  • 119,623
  • 25
  • 170
  • 301
Echchama Nayak
  • 971
  • 3
  • 23
  • 44

2 Answers2

1

Besides the nanoseconds, there is another caveat here: If I run

from datetime import date
timestamp = date.fromtimestamp(1571266800000000000/1e9)
print("Date =", timestamp)
>>> Date = 2019-10-17

note that this gives me the date in my local timezone (UTC+2). However, if you expect the date to refer to UTC (since seconds since the epoch should refer to UTC), you need to set the tzinfo property:

from datetime import datetime, timezone
timestamp = datetime.fromtimestamp(1571266800000000000/1e9, tz=timezone.utc)
print("Date =", timestamp.date())
>>> Date = 2019-10-16
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

Python expects seconds. The epochconverter gives me

Assuming that this timestamp is in nanoseconds (1 billionth of a second): GMT: Wednesday, 16. October 2019 23:00:00 Your time zone: Donnerstag, 17. Oktober 2019 01:00:00 GMT+02:00 DST Relative: 9 months ago

So I think what you should use in Python is:

date.fromtimestamp(15712668)
ashcatch
  • 2,327
  • 1
  • 18
  • 29
  • *Python expects seconds* - well, if you use e.g. the `pandas` package, `pd.to_datetime(1571266800000000000)` works pretty well ;-) – FObersteiner Jul 20 '20 at 13:01