question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FastAPI doesn't format datetime.datetime output to ISO 8601 as documented

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from pydantic import BaseModel
from fastapi import FastAPI
import datetime


class TestOutput(BaseModel):
    date: datetime.datetime

def app():
    fast_api_app = FastAPI()

    @fast_api_app.get("/", response_model=TestOutput)
    def test():
        return {'date': datetime.datetime.utcnow()}

    return fast_api_app

Description

Opening the web browser, I got the response:

{
  "date": "2022-06-14T19:25:55.821177"
}

The timezone information is missing, I expected “+00:00” in the end

The docs indicates that I should receive an ISO 8601 formatted date, that includes timezone https://fastapi.tiangolo.com/tutorial/extra-data-types/

Even the example provided in OpenAPI (/docs) have the timezone information as the follow:

{
  "date": "2022-06-14T19:25:55.846Z"
}

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.75.0

Python Version

3.8.10

Additional Context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
slacknercommented, Jun 15, 2022

A small side note, there is no need to use pytz to generate timezone aware timestamps. You can also use:

datetime.datetime.now(datetime.timezone.utc)
1reaction
slacknercommented, Jun 15, 2022

You can add a custom pydantic type to achieve that. See the following code snippet as an example:

from pydantic import BaseModel
from pydantic.datetime_parse import parse_datetime
from fastapi import FastAPI
import datetime

class UTCDatetime(datetime.datetime):
    @classmethod
    def __get_validators__(cls):
        yield parse_datetime  # default Pydantic behavior
        yield cls.validate

    @classmethod
    def validate(cls, value) -> str:
        if value.tzinfo is None:
            return value.replace(tzinfo=datetime.timezone.utc)

        # Convert to UTC
        return value.astimezone(datetime.timezone.utc)
        # or alternatively, return the original value:
        # return value

class TestOutput(BaseModel):
    date: UTCDatetime

def app():
    fast_api_app = FastAPI()

    @fast_api_app.get("/", response_model=TestOutput)
    def test():
        return {'date': datetime.datetime.utcnow()}

    return fast_api_app

As long as you are careful where you are using timezone-aware and non-timezone-aware timestamps, using such an approach is fine.

(Note: I’m using this myself, but for input parameters instead of output parameters. The type hint datetime.datetime accepts both timezone-aware and non-timezone-aware timestamps, and comparing both in the API endpoint can lead to an exception otherwise.)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Python FastAPI ISO 8601 Date format gets http:422 ...
I am calling the server from a Java client and am getting "422 Unprocessable Entity" This is way to strict!
Read more >
JSON Compatible Encoder - FastAPI
So, a datetime object would have to be converted to a str containing the data in ISO format. The same way, this database...
Read more >
Date and Time — Babel 2.11.0 documentation
... Time Formatting¶. babel.dates.format_datetime(datetime=None, format='medium', tzinfo=None, ... Return a date formatted according to the given pattern.
Read more >
Types, Functions, and Operators for Dates and Times - EdgeDB
All the date/time types are restricted to years between 1 and 9999, including the end points. Although many systems support ISO 8601 date...
Read more >
YAML: The Missing Battery in Python
Note: JSON is the only data format that doesn't support comments. ... YAML understands various date and time formats, including the ISO 8601...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found