Pydantic datetime format

Pydantic DateTime Format

Pydantic is a library for data validation and settings management based on Python type hints. It includes support for parsing and formatting of dates and times using the datetime module in Python.

Pydantic provides a DateTime type which can be used to validate and parse datetime strings according to a specified format. The format is specified using the strptime format codes, which are similar to the format codes used by the datetime.strptime() function.

Here is an example of how to use Pydantic DateTime and specify a custom format:


from datetime import datetime
from pydantic import BaseModel

class Event(BaseModel):
    event_date: datetime

# Create an instance of Event and provide a datetime string with a custom format
event = Event(event_date="2022-12-31 23:59:59")

# Pydantic will automatically parse the string using the specified format
print(event.event_date)  # Output: 2022-12-31 23:59:59

The DateTime field in the Event class accepts a datetime string in the format “YYYY-MM-DD HH:MM:SS” by default. However, you can specify a custom format using the `datetime_format` argument:


from datetime import datetime
from pydantic import BaseModel, Field

class Event(BaseModel):
    event_date: datetime = Field(datetime_format="%Y/%m/%d %H:%M:%S")

# Create an instance of Event and provide a datetime string with the custom format
event = Event(event_date="2022/12/31 23:59:59")

# Pydantic will parse the string using the specified custom format
print(event.event_date)  # Output: 2022-12-31 23:59:59

In the above example, we have specified the datetime_format as “%Y/%m/%d %H:%M:%S”, which indicates that the datetime string should have the format “YYYY/MM/DD HH:MM:SS”. Pydantic will parse the provided string accordingly.

By default, Pydantic DateTime fields also support various ISO 8601 formats, such as “YYYY-MM-DDTHH:MM:SS”, “YYYY-MM-DDTHH:MM:SSZ”, etc. These formats can be used without explicitly specifying the datetime_format.

That’s how you can use Pydantic to validate and parse datetime strings with custom formats. It offers flexibility in working with different date and time formats while ensuring data integrity.

Leave a comment