Last active
November 20, 2020 14:09
-
-
Save 9seconds/0ce5229851a2357807cd4100e8d6a4cc to your computer and use it in GitHub Desktop.
Example of inlined datetime comparators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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