|
| 1 | +import operator |
| 2 | +from datetime import date, datetime, time |
| 3 | +from typing import Any, Optional, Type, Union |
| 4 | + |
| 5 | +import dateutil.parser |
| 6 | + |
| 7 | +from .string_serializable import StringSerializable, StringSerializableRegistry, registry |
| 8 | + |
| 9 | +_dt_args_getter = operator.attrgetter('year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'tzinfo') |
| 10 | +_d_args_getter = operator.attrgetter('year', 'month', 'day') |
| 11 | +_t_args_getter = operator.attrgetter('hour', 'minute', 'second', 'microsecond', 'tzinfo') |
| 12 | + |
| 13 | + |
| 14 | +def extend_datetime(d: Union[date, time, datetime], cls: Union[Type[date], Type[time], Type[datetime]]) -> Any: |
| 15 | + """ |
| 16 | + Wrap datetime object into datetime subclass |
| 17 | +
|
| 18 | + :param d: date/time/datetime instance |
| 19 | + :param cls: datetime subclass |
| 20 | + :return: |
| 21 | + """ |
| 22 | + if isinstance(d, datetime): |
| 23 | + args = _dt_args_getter |
| 24 | + elif isinstance(d, time): |
| 25 | + args = _t_args_getter |
| 26 | + else: |
| 27 | + args = _d_args_getter |
| 28 | + return cls(*args(d)) |
| 29 | + |
| 30 | + |
| 31 | +_check_values_date = ( |
| 32 | + datetime(2018, 1, 2, 0, 4, 5, 678, tzinfo=None), |
| 33 | + datetime(2018, 1, 2, 9, 4, 5, 678, tzinfo=None) |
| 34 | +) |
| 35 | + |
| 36 | + |
| 37 | +def is_date(s: str) -> Optional[date]: |
| 38 | + """ |
| 39 | + Return date instance if given string is a date and None otherwise |
| 40 | +
|
| 41 | + :param s: string |
| 42 | + :return: date or None |
| 43 | + """ |
| 44 | + # dateutil.parser.parse replaces missing parts of datetime with values from default value |
| 45 | + # so if there is hour part in given string then d1 and d2 would be equal and string is not pure date |
| 46 | + d1 = dateutil.parser.parse(s, default=_check_values_date[0]) |
| 47 | + d2 = dateutil.parser.parse(s, default=_check_values_date[1]) |
| 48 | + return None if d1 == d2 else d1.date() |
| 49 | + |
| 50 | + |
| 51 | +_check_values_time = ( |
| 52 | + datetime(2018, 10, 11), |
| 53 | + datetime(2018, 12, 30) |
| 54 | +) |
| 55 | + |
| 56 | + |
| 57 | +def is_time(s: str) -> Optional[time]: |
| 58 | + """ |
| 59 | + Return time instance if given string is a time and None otherwise |
| 60 | +
|
| 61 | + :param s: string |
| 62 | + :return: time or None |
| 63 | + """ |
| 64 | + d1 = dateutil.parser.parse(s, default=_check_values_time[0]) |
| 65 | + d2 = dateutil.parser.parse(s, default=_check_values_time[1]) |
| 66 | + return None if d1 == d2 else d1.time() |
| 67 | + |
| 68 | + |
| 69 | +class IsoDateString(StringSerializable, date): |
| 70 | + """ |
| 71 | + Parse date using dateutil.parser.isoparse. Representation format always is ``YYYY-MM-DD``. |
| 72 | + You can override to_representation method to customize it. Just don't forget to call registry.remove(IsoDateString) |
| 73 | + """ |
| 74 | + |
| 75 | + @classmethod |
| 76 | + def to_internal_value(cls, value: str) -> 'IsoDateString': |
| 77 | + if not is_date(value): |
| 78 | + raise ValueError(f"'{value}' is not valid date") |
| 79 | + dt = dateutil.parser.isoparse(value) |
| 80 | + return extend_datetime(dt.date(), cls) |
| 81 | + |
| 82 | + def to_representation(self): |
| 83 | + return self.isoformat() |
| 84 | + |
| 85 | + def replace(self, *args, **kwargs) -> 'IsoDateString': |
| 86 | + # noinspection PyTypeChecker |
| 87 | + return date.replace(self, *args, **kwargs) |
| 88 | + |
| 89 | + |
| 90 | +class IsoTimeString(StringSerializable, time): |
| 91 | + """ |
| 92 | + Parse time using dateutil.parser.parse. Representation format always is ``hh:mm:ss.ms``. |
| 93 | + You can override to_representation method to customize it. |
| 94 | + """ |
| 95 | + |
| 96 | + @classmethod |
| 97 | + def to_internal_value(cls, value: str) -> 'IsoTimeString': |
| 98 | + t = is_time(value) |
| 99 | + if not t: |
| 100 | + raise ValueError(f"'{value}' is not valid time") |
| 101 | + return extend_datetime(t, cls) |
| 102 | + |
| 103 | + def to_representation(self): |
| 104 | + return self.isoformat() |
| 105 | + |
| 106 | + def replace(self, *args, **kwargs) -> 'IsoTimeString': |
| 107 | + # noinspection PyTypeChecker |
| 108 | + return time.replace(self, *args, **kwargs) |
| 109 | + |
| 110 | + |
| 111 | +class IsoDatetimeString(StringSerializable, datetime): |
| 112 | + """ |
| 113 | + Parse datetime using dateutil.parser.isoparse. |
| 114 | + Representation format always is ``YYYY-MM-DDThh:mm:ss.ms`` (datetime.isoformat method). |
| 115 | + """ |
| 116 | + |
| 117 | + @classmethod |
| 118 | + def to_internal_value(cls, value: str) -> 'IsoDatetimeString': |
| 119 | + dt = dateutil.parser.isoparse(value) |
| 120 | + return extend_datetime(dt, cls) |
| 121 | + |
| 122 | + def to_representation(self): |
| 123 | + return self.isoformat() |
| 124 | + |
| 125 | + def replace(self, *args, **kwargs) -> 'IsoDatetimeString': |
| 126 | + # noinspection PyTypeChecker |
| 127 | + return datetime.replace(self, *args, **kwargs) |
| 128 | + |
| 129 | + |
| 130 | +def register_datetime_classes(registry: StringSerializableRegistry = registry): |
| 131 | + """ |
| 132 | + Register datetime classes in given registry (using default registry if no arguments is passed). |
| 133 | + Date parsing is expensive operation so this classes are disabled by default |
| 134 | + """ |
| 135 | + registry.add(cls=IsoDateString) |
| 136 | + registry.add(cls=IsoTimeString) |
| 137 | + registry.add(cls=IsoDatetimeString) |
0 commit comments