Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting postgresql timestamp to JavaScript timestamp in Python

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

Now the problem I have is that flot can automatically handle the date using JavaScript's TIMESTAMP, but I don't know how to convert the Postgre timestamps to JavaScript TIMESTAMP (YES a timestamp, not a date stop 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 a way to do this?

like image 971
Sergio Ayestarán Avatar asked Feb 22 '13 19:02

Sergio Ayestarán


2 Answers

Use date_part or extract in postgres to return a timestamp.

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

Then you can just send that on over directly, noting that epoch is seconds since Jan 1, 1970, whereas JS wants milliseconds, thus the *1000. If you need it to actually be a date, once you receive it in Javascript, you can convert it to a date by calling new Date(timestamp_from_pg).

Note that flot can work off of timestamps as numbers, no need to actually create Date objects.

like image 198
Ryley Avatar answered Nov 12 '22 03:11

Ryley


You can't send a Python or Javascript "datetime" object over JSON. JSON only accepts more basic data types like Strings, Ints, and Floats.

The way I usually do it is send it as text, using Python's datetime.isoformat() then parse it on the Javascript side.

like image 29
Chris Dutrow Avatar answered Nov 12 '22 05:11

Chris Dutrow