Skip to content

Instantly share code, notes, and snippets.

@edo248
Last active September 26, 2019 20:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edo248/73975a3e0bd7872dcd896fa92954e8aa to your computer and use it in GitHub Desktop.
Save edo248/73975a3e0bd7872dcd896fa92954e8aa to your computer and use it in GitHub Desktop.
custom python datetime object with default format
# 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