0

+00:00" is a valid ISO 8601 timezone designation for UTC. But this seems to have changed to Z in latest fastapi=0.100.0. Is there a way to change this back?

In fastapi==0.95.0 we created our ISO date like this and returned it as json:

expiry_date = (device.expires_at.replace(tzinfo=pytz.UTC)).isoformat()
return {
    "expires_at": expiry_date
}

The unit test was expecting a dateformat like this: 2023-07-16T06:26:30.769459+00:00

assert response.json()["expires_at"] == date.strftime(
    "%Y-%m-%dT%H:%M:%S.%f+00:00"
)

But now with fastapi==0.100.0 the format has changed, which fails the unit test. 2023-07-16T06:26:30.769459Z

Is there a way to change this back to +00:00?

Houman
  • 64,245
  • 87
  • 278
  • 460
  • How about fixing your tests to be less rigid? – user3840170 Jul 15 '23 at 09:27
  • Because this is already in production and the mobile devices expect the date to be in that format in the JSON, which may cause crashes. – Houman Jul 15 '23 at 09:33
  • See https://stackoverflow.com/questions/66548586/how-to-change-date-format-in-pydantic for how you can define a custom serializer for datetime as necessary. (including an example with `@field_serializer` for v2. – MatsLindh Jul 15 '23 at 12:23
  • Don't think so. The issue happens when transforming datetime into json. – Houman Jul 15 '23 at 14:37

1 Answers1

0

I think you have to manually format the datetime object before returning it in the response. So maybe something like this:

expiry_date = device.expires_at.replace(tzinfo=pytz.UTC)
expiry_date_str = expiry_date.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")
return {
    "expires_at": expiry_date_str
}

Howerver this approach may make your API less compliant with ISO 8601. So you might want to consider updating your tests to accept 'Z' as a valid representation of UTC time, especially if other parts of your system (or external systems interacting with your API) are expecting this standard representation. So, your test could look something like this:

assert response.json()["expires_at"] == date.strftime(
    "%Y-%m-%dT%H:%M:%S.%fZ"
)
Edoardo Balducci
  • 332
  • 1
  • 10