Last active
September 26, 2019 20:07
-
-
Save edo248/73975a3e0bd7872dcd896fa92954e8aa to your computer and use it in GitHub Desktop.
custom python datetime object with default format
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
# Custom datetime class that can be initialized by date string and has default format | |
# useful for automatic serialization/deserializaion (to JSON, or other formats) such that | |
# when deserialized constructore can be called directly CustomDate(<string>) and serialization is just str() | |
import datetime | |
class CustomDate(datetime.datetime): | |
__date_format = '%Y/%m/%d' | |
def __new__(cls, *args, **kwargs): | |
if args and type(args[0]) == str: | |
d = datetime.datetime.strptime(args[0], cls.__date_format) | |
me = super().__new__(cls, d.year, d.month, d.day, d.hour, d.minute, d.second) | |
else: | |
me = super().__new__(cls, *args, **kwargs) | |
return me | |
def __repr__(self): | |
return self.__format__(self.__date_format) | |
if __name__ == '__main__': | |
a = CustomDate('2019/1/1') | |
b = CustomDate(2019, 1, 1) | |
print(a) | |
print(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment