Python

How to Manage DateTime with Pydantic

Pydantic helps with the DateTime data in Python. It’s like a helpful tool that makes handling the info easier. It makes a plan for our data; the plan shows how our DateTime information looks like dates and times. Pydantic checks and understands the information. We can also add rules for different DateTime styles or time zones. Plans help turn our DateTime information into a special style called JSON and back. If things go wrong, Pydantic tells us what’s happening so we can fix it. With Pydantic, dealing with the DateTime data becomes simple, and we make fewer mistakes with time things in Python.

Method 1: Manage the Date and Time Information with Pydantic

Handling the date and time information in Python becomes simpler and more organized with the assistance of Pydantic. Pydantic acts like a helpful guide that ensures data accuracy and minimizes errors, making it an essential tool for managing the DateTime data effectively. Let’s look into an example and explore how we can manage the date and time with Pydantic.

To begin importing Pydantic, we need to make Pydantic available in our Python environment. This is done by importing the Pydantic library with the following lines:

!pip install pydantic

from pydantic import BaseModel

from datetime import datetime

These lines help us in the installation of all the Pydantic packages in our project.

Next, we create a “datetime” class model. This could be imagined as planning a project and making a list of all the things that we need. Similarly, with Pydantic, we create a model for our data. We design a class that builds upon Pydantic’s features. For instance:

class DateTimeModel(BaseModel):

datentime: datetime

This is like asking Pydantic that we want to have a required field called “datentime” which holds the dates and times.

Now, to ensure the validation and understanding of the data, Pydantic works like a careful instructor. When we give it an information, it verifies that the data is correct. For example:

data = {"datentime": "2023-08-22 15:30:00"}

  validator = DateTimeModel(**data)

This is similar to applying the conditions on Pydantic to check if the data and time that we mentioned are still on the list or if they are correct. This is done by creating an instance for the DateTime model for the Pydantic to validate our specified options.

We can always add our own rules that are customized according to our needs. Though Pydantic always validates our data automatically, we may sometimes encounter diverse DateTime formats where we want to meet the specific conditions as validating the DateTime formats by checking the time zone. At this point, we may use the Pydantic’s custom validator which is the “field_validator”. We can tell Pydantic about our additional requirements such as special checks. For instance:

from pydantic import field_validator

class CustomDateTimeModel(BaseModel):

  date_and_time: datetime

We need to import the “field_validator” from Pydantic’s installed packages to apply the customized set of rules. Pydantic assists us with something extra that we want to perform as a special check.

@field_validator("date_and_time")

def checktimezone(cls, value):

  # We can include our special checks here

  return value

Transformation and reverting of the data is changing the format of the data, e.g. conversion into strings or converting it back to the original format. Pydantic also has a knack for converting the data into different “styles”. With Pydantic, we can do something similar with our data. Let’s see how this works using the example of changing the formats.

Suppose our DateTime data is neatly stored in a Pydantic model named “DateTimeModel”. We validated and checked it, and now we want to share it with others or store it in a certain way. This is where Pydantic’s transformation skills come in and solve our issues.

We can easily transform our validated DateTime data into a different style called JSON. JSON is a format that’s easy for computers to understand which makes it great for sharing and storing the data. Here’s how we can do it:

json_data = validator.model_dump_json()

print(json_data)

In this line of code, the “validated_data” is the instance of our “DateTimeModel” that is validated using Pydantic. When we call “.json()” on it, Pydantic transforms our data into a JSON-formatted string. This is like changing our favorite language text into some other language that’s universally easy to understand.

Later on, if we want to use our data in its original form again, we can revert it from JSON back to the regular style. It’s like changing back to our original text language after the special event. To do this, we can use Pydantic’s built-in method called “model_validate_json”:

original_data = DateTimeModel.model_validate_json(json_data)

print(original_data)

In this line, “json_data” is the JSON-formatted string that we obtained earlier. When we use the “model_validate_json” on it, Pydantic turns the JSON data back into the familiar format of our “DateTimeModel”.

So, Pydantic is like a format converter for our data. It can help us change our data’s format into something more suitable for sharing or storage (JSON). When we need it in its original form again, Pydantic can help us change it back. This capability makes Pydantic a versatile tool for managing the DateTime data while ensuring that it remains easy to work with and share. Here is the full code with an output for the example:

from pydantic import BaseModel
from datetime import datetime

class DateTimeModel(BaseModel):
    datentime: datetime
data = {"datentime": "2023-08-22 15:30:00"}
validator = DateTimeModel(**data)
from pydantic import field_validator

class CustomDateTimeModel(BaseModel):
    date_and_time: datetime

    @field_validator("date_and_time")
    def checktimezone(cls, value):
        # We can include our special checks here
        return value
json_data = validator.model_dump_json()
print(json_data)
original_data = DateTimeModel.model_validate_json(json_data)
print(original_data)

Method 2: Manage the Schedule Planner with Pydantic’s DateTime

Suppose we’re building a schedule planner to help people remember stuff like meetups and plans. To make it work fantastically, especially with dates and times, we decided to use Pydantic.

Getting started requires calling Pydantic, like inviting a smart guide who knows how to put things in order. We can start by typing the “from pydantic import BaseModel” code at the very start.

from pydantic import BaseModel

from datetime import datetime

Then, we make a plan/model for the data; it’s like making a list before implementing a project. We create a plan for what the dates and times should be. We make a special class called “SchedulePlan” using Pydantic:

class schedule plan(BaseModel):

event_name: str

datentime: datetime

Here, we ask Pydantic that we’re going to have names for the events and dates with times.

For the data validation, Pydantic automatically checks by creating the instance of the model. When someone adds an information about an event, Pydantic checks if the date and time are written right. For example:

data = {"event_name": "meeting", "datentime": "2023-10-10 14:30:00"}

validated_event = schedulePlan(**data)

Pydantic makes sure that the date and time look good and are in the right format.

To add the special rules (if we want); sometimes we want special rules for extra plans. Pydantic gets this as well. For instance, we only want to add events for the future. We can do this with a special rule:

from pydantic import field_validator

class upcoming_schedulePlan(BaseModel):

  event_name: str

  date_and_time: datetime

  @field_validator("datentime")

  def check_future_date(cls, value):

    if value <= datetime.now():

        raise ValueError("Events should be in the future")

    return value

In the provided code, Pydantic helps to ensure that no event is added for a time that’s already done.

With Pydantic, our schedule planner app becomes a date and time master/pro. It checks everything, follows the special rules if we need them, and helps us keep track of important meetups. Pydantic makes sure that everything works great in our events.

Complete the code for the example with a snippet of the output:

from pydantic import BaseModel

from datetime import datetime

class scheduleplan(BaseModel):

  event_name: str

  datentime: datetime

data = {"event_name": "meeting", "datentime": "2023-10-10 14:30:00"}

validated_event = scheduleplan(**data)

print(validated_event)

from pydantic import field_validator

class upcoming_schedulePlan(BaseModel):

  event_name: str

  datentime: datetime

  @field_validator("datentime")

def check_future_date(cls, value):

  if value <= datetime.now():

  raise ValueError("Events are in future")

  return value

Conclusion

In a nutshell, Pydantic is a great tool for handling the dates and times in Python. It makes dealing with these details super easy by keeping things organized, checking if everything’s right, and helping us change the formats if needed. With Pydantic, we can create a plan for our data, make sure it’s accurate, and even set special rules if we want to. This guide shows how to manage the date and time using Pydantic with the help of two examples. Whether we’re planning for events or keeping track of appointments, Pydantic makes working with dates and times very easy.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.