1import datetime
2
3import dateutil
4from dateutil.parser import parse
5import pytz
6
7from taskw.utils import DATE_FORMAT
8
9from .base import Field
10
11
12class DateField(Field):
13    def deserialize(self, value):
14        if not value:
15            return value
16        value = parse(value)
17        if not value.tzinfo:
18            value = value.replace(tzinfo=pytz.utc)
19        return value
20
21    def serialize(self, value):
22        if isinstance(value, datetime.datetime):
23            if not value.tzinfo:
24                #  Dates not having timezone information should be
25                #  assumed to be in local time
26                value = value.replace(tzinfo=dateutil.tz.tzlocal())
27            #  All times should be converted to UTC before serializing
28            value = value.astimezone(pytz.utc).strftime(DATE_FORMAT)
29        elif isinstance(value, datetime.date):
30            value = value.strftime(DATE_FORMAT)
31        return value
32