Skip to content

Commit

Permalink
Merge pull request #95 from claydugo/allow_utc_timezone
Browse files Browse the repository at this point in the history
Allow timezone.utc as the timezone in datetime and time objects
  • Loading branch information
mverleg authored Aug 19, 2023
2 parents c0ffeeb + 15c1821 commit 98ec6b2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 8 additions & 2 deletions json_tricks/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,20 @@ def json_date_time_encode(obj, primitives=False):
('day', obj.day), ('hour', obj.hour), ('minute', obj.minute),
('second', obj.second), ('microsecond', obj.microsecond)])
if obj.tzinfo:
dct['tzinfo'] = obj.tzinfo.zone
if hasattr(obj.tzinfo, 'zone'):
dct['tzinfo'] = obj.tzinfo.zone
else:
dct['tzinfo'] = obj.tzinfo.tzname(None)
elif isinstance(obj, date):
dct = hashodict([('__date__', None), ('year', obj.year), ('month', obj.month), ('day', obj.day)])
elif isinstance(obj, time):
dct = hashodict([('__time__', None), ('hour', obj.hour), ('minute', obj.minute),
('second', obj.second), ('microsecond', obj.microsecond)])
if obj.tzinfo:
dct['tzinfo'] = obj.tzinfo.zone
if hasattr(obj.tzinfo, 'zone'):
dct['tzinfo'] = obj.tzinfo.zone
else:
dct['tzinfo'] = obj.tzinfo.tzname(None)
elif isinstance(obj, timedelta):
if primitives:
return obj.total_seconds()
Expand Down
4 changes: 3 additions & 1 deletion tests/test_tz.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,21 @@
work with just Python code functionality, and are tested in `nonp`.
"""

from datetime import datetime, date, time, timedelta
from datetime import datetime, date, time, timedelta, timezone
from json_tricks import dumps, loads
from json_tricks.utils import is_py3
import pytz


DTOBJ = [
datetime(year=1988, month=3, day=15, hour=8, minute=3, second=59, microsecond=7),
datetime.now(timezone.utc),
pytz.UTC.localize(datetime(year=1988, month=3, day=15, minute=3, second=59, microsecond=7)),
pytz.timezone('Europe/Amsterdam').localize(datetime(year=1988, month=3, day=15, microsecond=7)),
date(year=1988, month=3, day=15),
time(hour=8, minute=3, second=59, microsecond=123),
time(hour=8, second=59, microsecond=123, tzinfo=pytz.timezone('Europe/Amsterdam')),
time(hour=8, second=59, microsecond=123, tzinfo=timezone.utc),
timedelta(days=2, seconds=3599),
timedelta(days=0, seconds=-42, microseconds=123),
[{'obj': [pytz.timezone('Europe/Amsterdam').localize(datetime(year=1988, month=3, day=15, microsecond=7))]}],
Expand Down

0 comments on commit 98ec6b2

Please sign in to comment.