Skip to content

Commit 30b509a

Browse files
committed
Make datetime properties timezone-aware
1 parent 480349c commit 30b509a

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

github3/models.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from requests.compat import urlparse, is_py2
1313
from github3.decorators import requires_auth
1414
from github3.session import GitHubSession
15+
from github3.utils import UTC
1516
from datetime import datetime
1617
from logging import getLogger
1718

@@ -36,9 +37,12 @@ def to_json(self):
3637
return self._json_data
3738

3839
def _strptime(self, time_str):
39-
"""Converts an ISO 8601 formatted string into a datetime object."""
40+
"""Convert an ISO 8601 formatted string in UTC into a
41+
timezone-aware datetime object."""
4042
if time_str:
41-
return datetime.strptime(time_str, __timeformat__)
43+
# Parse UTC string into naive datetime, then add timezone
44+
dt = datetime.strptime(time_str, __timeformat__)
45+
return dt.replace(tzinfo=UTC())
4246
return None
4347

4448
def _repr(self):

github3/utils.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# -*- coding: utf-8 -*-
22
from collections import Callable
3-
from datetime import datetime
3+
from datetime import datetime, timedelta, tzinfo
44
from requests.compat import basestring
55
import re
66

@@ -30,6 +30,25 @@ def timestamp_parameter(timestamp, allow_none=True):
3030
raise ValueError("Cannot accept type %s for timestamp" % type(timestamp))
3131

3232

33+
class UTC(tzinfo):
34+
"""Yet another UTC reimplementation, to avoid a dependency on pytz or
35+
dateutil."""
36+
37+
_ZERO = timedelta(0)
38+
39+
def __repr__(self):
40+
return 'UTC()'
41+
42+
def dst(self, dt):
43+
return self._ZERO
44+
45+
def tzname(self, dt):
46+
return 'UTC'
47+
48+
def utcoffset(self, dt):
49+
return self._ZERO
50+
51+
3352
def stream_response_to_file(response, path=None):
3453
pre_opened = False
3554
fd = None

tests/test_models.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ def test_boolean(self):
3636

3737
self.assertRaises(github3.GitHubError, self.g._boolean, r, 200, 404)
3838

39+
def test_strptime(self):
40+
dt = self.g._strptime('2013-06-18T19:53:04Z')
41+
assert dt.tzname() == 'UTC'
42+
assert dt.dst().total_seconds() == 0
43+
assert dt.utcoffset().total_seconds() == 0
44+
3945

4046
class TestGitHubError(TestCase):
4147
def __init__(self, methodName='runTest'):

0 commit comments

Comments
 (0)