I am using Python's requests module to fetch data from a website. In the JSON response object, I have a key created at
and its value is 1520369492984
.I am totally lost as to how to convert this to a Datetime object in Python. pd.to_datetime
failed. Any pointers on this would be much appreciated! Thank you!
Asked
Active
Viewed 435 times
0

Gingerbread
- 1,938
- 8
- 22
- 36
-
Possible duplicate of [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – pault Mar 29 '18 at 15:31
-
@pault: I tried but that raised a `ValueError` saying `year is out of range`. – Gingerbread Mar 29 '18 at 15:35
-
3You should consult the documentation for the API to see what format the value is in. That said, it *appears* to be a regular UNIX timestamp with milliseconds appended (i.e., an integer-encode version of `1520369492.984`). – chepner Mar 29 '18 at 15:37
-
3Try `datetime.fromtimestamp(1520369492984/1000)` – pault Mar 29 '18 at 15:37
-
@chepner : Great thanks! There is no proper documentation for this part but the conversion produced the exact date! Thank you! – Gingerbread Mar 29 '18 at 15:47
-
Arguably, such a value shouldn't be used at all, preferring instead something defined by [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). – chepner Mar 29 '18 at 16:07
1 Answers
1
What you're getting is called epoch
Date Time.
import time
time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(1520369492984/1000))
Or using the datetime
module:
import datetime
datetime.datetime.utcfromtimestamp(1520369492984/1000).replace(tzinfo=datetime.timezone.utc)
Background Story:
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1/1/1970), but 'epoch' is often used as a synonym for 'Unix time'.
You can find online converters for the same. My personal recommendation: epoch converter
The above not only converts the timestamp but also, gives you code snippets for different languages.

iam.Carrot
- 4,976
- 2
- 24
- 71
-
Great! This format is what I was looking for! Thanks for the notes as well! – Gingerbread Mar 29 '18 at 15:53
-
1
-
:) Same pinch! I am from the same country as you!! And thank you again!! – Gingerbread Mar 29 '18 at 15:56
-
-