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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With