How to ensure that the timezone is entered in the ISO UTC format within the request body?

Question:

I am using pydantic within FastAPI and I need to ensure that the timestamp is always entered in the UTC ISO format such as 2015-09-01T16:09:00:000Z.

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field
from datetime import datetime


app = FastAPI()

measurements = [
    {
      "timestamp": "2015-09-01T16:09:00:000Z",
      "temperature": 27.1
    },
    {
        "timestamp": "2016-09-01T16:09:00:000Z",
        "temperature": 21.3
    }
]

class MeasurementIn(BaseModel):
    timestamp: datetime
    temperature: Optional[float]    

@app.post("/measurements")
async def create_measurement(m: MeasurementIn, response: Response):
    measurements.append(m)

The above code is working but it is also accepting datetime in other formats. I want to strictly restrict it to UTC ISO Format. I have tried to change the timestamp to timestamp: datetime.utcnow().isoformat() but it is not working.

Asked By: meallhour

||

Answers:

Import re

import re

Declare the regular expression

timestamp_regex = r'[0-9]{4}-[0-9]{2}-[0-9]{2}T([0-9]{2}:){3}[0-9]{3}Z'

Check the parameter (note that this assumes m is a valid dictionary)

@app.post("/measurements")
async def create_measurement(m: MeasurementIn, response: Response):
  if bool(re.match(timestamp_regex, m["timestamp"])):
    measurements.append(m)
  else:
    # we have an error that needs to be handled
Answered By: ChrisSc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.