I am working on an API and i’m trying to create a Flask route to fetch my data but there is a problem.
When converting my dataframe into a json. The date column ‘Mon, 15 Apr 2024 11:20:20 GMT’ becomes 1713177478000.
Do i have to create my json myself if i want timestamp to keep its state ?
@app.route("/tipi", methods=["GET"])
def sqltipi():
try:
department = request.args.get("department")
ogc_fid = request.args.get("ogc_fid")
score = request.args.get("score")
longitude = request.args.get("longitude")
latitude = request.args.get("latitude")
rayon = request.args.get("rayon")
if longitude is not None and latitude is not None and rayon is not None:
df= DBP.load_point_rayon_tipi(longitude,latitude,rayon)
elif ogc_fid is not None:
df = DBP.load_brigades_tipi(ogc_fid)
else:
df = DBP.load_tipi(department)
if score is not None:
df = df[df["score"] == int(score)]
js = json.loads(df.to_json(orient="records"))
return js
except Exception as e:
error_message = "An error occurred: " + str(e)
return jsonify({"error": error_message}), 500
2
Answers
The behavior you’re observing where the date column ‘Mon, 15 Apr 2024 11:20:20 GMT’ is converted into a large integer like 1713177478000 is due to how the pandas.DataFrame.to_json() method serializes datetime objects. By default, pandas converts datetime objects to milliseconds since the Unix epoch (January 1, 1970). This is a standard practice for handling date and time data in JSON because JSON itself does not have a built-in date type.
However, if you want to maintain the datetime in a more human-readable string format or a specific format within your JSON output, you can adjust the date_format parameter of the to_json() method. Here’s how you can modify your Flask route to handle this:
Use the date_format=’iso’ parameter in the to_json() method to convert the datetime objects to ISO 8601 string format, which is a widely accepted format for transmitting datetime information in web applications.
Ensure you return a response using Flask’s jsonify() to properly set the response headers and manage JSON serialization correctly.
You could pass the data_format property in df.to_json
js = json.loads(df.to_json(orient="records", date_format="iso"))