pythondatetimetimestampfacebook-messengerfacebook-messenger-bot

How do I convert the timestamp of Facebook "Message" object


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!


Solution

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

    import datetime
    datetime.datetime.fromtimestamp(ts/1000.0)