diff --git a/pendulum/pendulum.py b/pendulum/pendulum.py index c73e8c6a..74a04f5b 100644 --- a/pendulum/pendulum.py +++ b/pendulum/pendulum.py @@ -205,13 +205,13 @@ def instance(cls, dt, tz=UTC): # Checking for pytz/tzinfo if isinstance(tz, datetime.tzinfo) and not isinstance(tz, (Timezone, TimezoneInfo)): # pytz - if hasattr(tz, 'localize'): + if hasattr(tz, 'localize') and tz.zone: tz = tz.zone else: # We have no sure way to figure out # the timezone name, we fallback # on a fixed offset - tz = dt.utcoffset().total_seconds() / 3600 + tz = tz.utcoffset(dt).total_seconds() / 3600 return cls( dt.year, dt.month, dt.day, diff --git a/tests/pendulum_tests/test_construct.py b/tests/pendulum_tests/test_construct.py index a1036383..ffb0059d 100644 --- a/tests/pendulum_tests/test_construct.py +++ b/tests/pendulum_tests/test_construct.py @@ -135,6 +135,25 @@ def test_instance_timezone_aware_datetime_pytz(self): ) self.assertEqual('Europe/Paris', now.timezone_name) + def test_instance_timezone_aware_datetime_pytz_offset(self): + # Impossible timezone of +21 (won't accidentally match the local offset) + fixed_offset = pytz.FixedOffset(21 * 60) + + now = Pendulum.instance( + datetime.now(fixed_offset) + ) + self.assertEqual(21, now.offset_hours) + + now = Pendulum.instance( + datetime.now(), fixed_offset + ) + self.assertEqual(21, now.offset_hours) + + now = Pendulum.instance( + datetime.now(fixed_offset), pytz.timezone('Europe/Paris') + ) + self.assertEqual(21, now.offset_hours) + def test_instance_timezone_aware_datetime_any_tzinfo(self): dt = datetime(2016, 8, 7, 12, 34, 56, tzinfo=tz.gettz('Europe/Paris')) now = Pendulum.instance(dt)