Skip to content

Commit fa40f64

Browse files
klardotshsdispater
authored andcommitted
Add support for stdlib datetime.timezone instances (#93)
* Add support for stdlib datetime.timezone instances * Turns out that test is only safe to run on >= 3.2 * Update PR after @sdispater feedback - Fixed a total_seconds() misuse - Simplified our fallback logic to always use utcoffset() when we have a tzinfo instance that isn't pytz - Added an additional assertion to our test, ensuring non-UTC `datetime.timezone` instances can be set * Remove unnecessary try/catch
1 parent 24fb178 commit fa40f64

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

pendulum/pendulum.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -70,16 +70,11 @@ def _safe_create_datetime_zone(cls, obj):
7070
elif isinstance(obj, datetime.tzinfo) and not isinstance(obj, Timezone):
7171
# pytz
7272
if hasattr(obj, 'localize'):
73-
obj = obj.zone
74-
else:
75-
# We have no sure way to figure out
76-
# the timezone name, we raise an error
77-
78-
raise ValueError('Unsupported timezone {}'.format(obj))
73+
return cls._timezone(obj.zone)
7974

80-
tz = cls._timezone(obj)
75+
return FixedTimezone(obj.utcoffset(None).total_seconds())
8176

82-
return tz
77+
return cls._timezone(obj)
8378

8479
@classmethod
8580
def _local_timezone(cls):

tests/pendulum_tests/test_timezone.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
# -*- coding: utf-8 -*-
22

3+
import sys
34
from pendulum import Pendulum
45

56
from .. import AbstractTestCase
67

8+
if sys.version_info >= (3, 2):
9+
from datetime import timedelta, timezone
10+
711

812
class TimezoneTest(AbstractTestCase):
913

@@ -36,3 +40,12 @@ def test_astimezone(self):
3640
d = d.astimezone('Europe/Paris')
3741
self.assertEqual('Europe/Paris', d.timezone_name)
3842
self.assertPendulum(d, now.year, now.month, now.day, now.hour + 1, now.minute)
43+
44+
if sys.version_info >= (3, 2):
45+
d = d.astimezone(timezone.utc)
46+
self.assertEqual('+00:00', d.timezone_name)
47+
self.assertPendulum(d, now.year, now.month, now.day, now.hour, now.minute)
48+
49+
d = d.astimezone(timezone(timedelta(hours=-8)))
50+
self.assertEqual('-08:00', d.timezone_name)
51+
self.assertPendulum(d, now.year, now.month, now.day, now.hour - 8, now.minute)

0 commit comments

Comments
 (0)