Skip to content

Instantly share code, notes, and snippets.

@navhits
Last active March 15, 2021 10:51
Show Gist options
  • Save navhits/8ab16894ab58c7ce3eee553b29c9a292 to your computer and use it in GitHub Desktop.
Save navhits/8ab16894ab58c7ce3eee553b29c9a292 to your computer and use it in GitHub Desktop.
A demonstration of datetime validation and parsing in Python using Pydantic library. The code should be run as-is. You can make changes to the pydantic model if you'd like to see how it works.
from pydantic import BaseModel
from datetime import datetime
import time
class Model(BaseModel):
a: datetime
b : datetime
c : datetime
d : datetime
m = Model(
a = datetime.utcnow(), # Timezone unaware datetime objects
b = "2020-12-02 12:40:20.109784", # Datetime strings
c = time.time(), # Unix timestamps
d = '2021-03-04T10:28:50.809289+00:00' # ISO date time format strings
)
print(m.dict())
'''
{'a': datetime.datetime(2021, 3, 15, 10, 25, 52, 222624),
'b': datetime.datetime(2020, 12, 2, 12, 40, 20, 109784),
'c': datetime.datetime(2021, 3, 15, 10, 25, 52, 222630, tzinfo=datetime.timezone.utc),
'd': datetime.datetime(2021, 3, 4, 10, 28, 50, 809289, tzinfo=datetime.timezone.utc)}
'''
print(m.json())
'''
{"a": "2021-03-15T10:25:52.222624",
"b": "2020-12-02T12:40:20.109784",
"c": "2021-03-15T10:25:52.222630+00:00",
"d": "2021-03-04T10:28:50.809289+00:00"}
'''
# Alternatively you can also parse each objects seperately from the class. These will be JSON serialized by default.
print(m.a)
print(m.b)
print(m.c)
print(m.d)
# For more validation methods an about Pydantic, read their docs, https://pydantic-docs.helpmanual.io/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment