Skip to content

Instantly share code, notes, and snippets.

@9seconds
Last active November 20, 2020 14:09
Show Gist options
  • Save 9seconds/0ce5229851a2357807cd4100e8d6a4cc to your computer and use it in GitHub Desktop.
Save 9seconds/0ce5229851a2357807cd4100e8d6a4cc to your computer and use it in GitHub Desktop.
Example of inlined datetime comparators
import enum
import datetime
import pydantic
class Comparator(enum.Enum):
LT = "<"
GT = ">"
EQ = "="
NE = "~"
class ComparatorDatetime(pydantic.BaseModel):
timestamp: datetime.datetime
comparator: Comparator
@classmethod
def __get_validators__(cls):
yield cls._validate_format
@classmethod
def _validate_format(cls, value):
return cls.construct(
timestamp=datetime.datetime.fromisoformat(value[1:]),
comparator=Comparator(value[0]),
)
class MyModel(pydantic.BaseModel):
ff: ComparatorDatetime
model = MyModel(ff=">2020-11-20T00:00:00")
print(model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment