Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jsonify always returns datetime objects as GMT timezone #2857

Closed
wayneworkman opened this issue Jul 10, 2018 · 2 comments
Closed

Jsonify always returns datetime objects as GMT timezone #2857

wayneworkman opened this issue Jul 10, 2018 · 2 comments

Comments

@wayneworkman
Copy link

wayneworkman commented Jul 10, 2018

Issue

Jsonify always returns datetime objects as GMT timezone. Seems like this has been a problem in the past with these issues:

Environment

  • Python version: 2.7.5
  • Flask version: 1.0.2
  • Werkzeug version: 0.14.1
  • pytz version: 2018.5

Testcode

#!/usr/bin/env python2.7

from werkzeug.http import http_date
from datetime import datetime
import pytz

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def root():
    # Localize time
    local_time = pytz.timezone("America/Chicago")
    time = datetime.utcnow().replace(microsecond=0).replace(tzinfo=pytz.utc)
    time = time.astimezone(local_time)

    print("iso format:", time.isoformat())
    print("object:", time.tzinfo)
    print("http date:", http_date(time))

    result = [time]

    print("Test object: %s" % result)

    return jsonify(result)

app.run(host='127.0.0.1', port=8080, debug=False)

Console output:

Test object: [datetime.datetime(2018, 7, 10, 11, 45, 20, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>)]

Jsonify output:

["Tue, 10 Jul 2018 16:45:20 GMT"]
@davidism
Copy link
Member

That's the correct behavior. The default JSONEncoder accepts times with any timezone as input, but always outputs UTC (GMT) in RFC 1123 format.

In the vast majority of cases, you should be working with UTC at boundaries and converting to local time only when displaying to users.

If you want to change the format that dates are serialized, including supporting other timezones, override app.json_encoder with your own flask.json.JSONEncoder subclass.

@jhwinter
Copy link

According to this Stack Overflow answer, ISO 8601 is the preferred standard over RFC 1123/822/2822. This link further defines the current best practice.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 14, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants