Convert postgresql timestamp to JavaScript timestamp in Python

I have a postgre database with a timestamp column, and I have a Python REST service that executes a query in the database and returns data to the JavaScript interface to plot using flot .

Now the problem is that flot can automatically process the date using JavaScript TIMESTAMP, but I don't know how to convert Postgre timestamps to TIMESTAMP JavaScript (yes timestamp, not stopping date editing if you don't know the answer) in Python. I don't know if this is the best approach (maybe the conversion can be done in JavaScript?). Is there any way to do this?

+7
source share
2 answers

Use date_part or extract to postgres to return a timestamp.

 select date_part('epoch',mydatefield)*1000 from table; 

Then you can simply send it directly, noting that the epoch is seconds since January 1, 1970, while JS wants milliseconds, thus *1000 . If you need this to be a date, as soon as you receive it in Javascript, you can convert it to a date by calling new Date(timestamp_from_pg) .

Note that the fleet can work with timestamps as numbers; you do not need to create Date objects.

+7
source

You cannot send a Python or Javascript "datetime" object on top of JSON. JSON accepts only basic data types, such as strings, ints, and floats.

As usual I do this, send it as text using Python datetime.isoformat() , then parse it on the Javascript side.

+2
source

All Articles