Skip to content

Commit 13d2275

Browse files
committed
tests: check more timezones
1 parent 4cca280 commit 13d2275

File tree

2 files changed

+13
-15
lines changed

2 files changed

+13
-15
lines changed

include/pybind11/chrono.h

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -150,30 +150,21 @@ template <typename Duration> class type_caster<std::chrono::time_point<std::chro
150150
// Lazy initialise the PyDateTime import
151151
if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
152152

153-
// Declare these special duration types so the conversions happen with the correct primitive types (int)
154-
using us_t = duration<int, std::micro>;
155-
156-
// Get out microseconds, and make sure they are positive, to avoid bug in eastern hemisphere time zones
157-
// (cfr. https://github.com/pybind/pybind11/issues/2417)
158-
auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
159-
if (us.count() < 0)
160-
us += seconds(1);
161-
162-
// Subtract microseconds BEFORE `system_clock::to_time_t`, because:
163-
// > If std::time_t has lower precision, it is implementation-defined whether the value is rounded or truncated.
164-
// (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
165-
std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
153+
std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src));
166154
// this function uses static memory so it's best to copy it out asap just in case
167155
// otherwise other code that is using localtime may break this (not just python code)
168156
std::tm localtime = *std::localtime(&tt);
169157

158+
// Declare these special duration types so the conversions happen with the correct primitive types (int)
159+
using us_t = duration<int, std::micro>;
160+
170161
return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
171162
localtime.tm_mon + 1,
172163
localtime.tm_mday,
173164
localtime.tm_hour,
174165
localtime.tm_min,
175166
localtime.tm_sec,
176-
us.count());
167+
(duration_cast<us_t>(src.time_since_epoch() % seconds(1))).count());
177168
}
178169
PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));
179170
};

tests/test_chrono.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,14 @@ def test_chrono_system_clock_roundtrip_date():
8181
datetime.time(5, 59, 59, 0),
8282
datetime.time(5, 59, 59, 1),
8383
])
84-
def test_chrono_system_clock_roundtrip_time(time1):
84+
@pytest.mark.parametrize("tz", [
85+
"/usr/share/zoneinfo/Europe/Brussels",
86+
"/usr/share/zoneinfo/Asia/Pyongyang",
87+
"/usr/share/zoneinfo/America/New_York",
88+
])
89+
def test_chrono_system_clock_roundtrip_time(time1, tz, monkeypatch):
90+
monkeypatch.setenv("TZ", tz)
91+
8592
# Roundtrip the time
8693
datetime2 = m.test_chrono2(time1)
8794
date2 = datetime2.date()

0 commit comments

Comments
 (0)