How do I convert the timestamp of Facebook "Message" object
Asked Answered
W

1

5

I apologize if this turns out to be a really dumb question. I am reading a message object through the Facebook messenger API, using Flask in Python.

I first extract the timestamp after reading in the JSON object

# read the JSON from Flask "request" object    
input_json = request.get_json() 
# extract the timestamp
ts = input_json["entry"][0]["messaging"][0]["timestamp"]

Then I try to convert the result into a human-readable date format using datetime (docs), figuring this was a Unix timestamp, but it returns a ValueError: year is out of range.

import datetime
datetime.datetime.fromtimestamp(int(ts)))

Now turns out the specific message has a timestamp 1504129573859, which is in the future, when I check e.g. here.

The same error occurs when I feed it the timestamp given in the documentation (link above), which is 1458692752478 so I figure it's not an issue with my input parsing. I could not find anything regarding this on here or the FB docs and am grateful for any help!

  • Which time format is this, and how can I convert it to a datetime object?

  • Or is there something wrong with my approach / thinking?

Wilmoth answered 31/8, 2017 at 4:7 Comment(0)
I
10

You can convert fb's timestamp to python timestamp at first:

import datetime
datetime.datetime.fromtimestamp(ts/1000.0)
Imprecise answered 31/8, 2017 at 4:14 Comment(6)
No need to cast it to a int - you lose precision. In Py2 use ts/1000.0 (or from __future__ import division)Sentiment
Thank you sir, that totally solved it! Is there any specific reason for this * 1000 business?Wilmoth
Because facebook returns a timestamp in milliseconds since epoch. and fromtimestamp() takes secondsSentiment
You may find that it is in utc so you may need datetime.utcfromtimestamp()Sentiment
@Sentiment that makes a lot of sense, thanks for the helpful comments!Wilmoth
No need to cast to int in c#. I used it in milliseconds.Darius

© 2022 - 2024 — McMap. All rights reserved.