Skip to content

Commit b227215

Browse files
committed
avoid leaking Python handle in timestamp conversion
Adding UTC to a datetime object creates a new Python object. We therefore need to get rid of the original one. Fixes #139.
1 parent a31cd57 commit b227215

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

lib/cast.h

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,19 @@ namespace pybind11 { namespace detail {
4141

4242
std::time_t tt = src.seconds_since_epoch();
4343
std::tm localtime = *std::gmtime(&tt);
44-
4544
handle pydate = PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
46-
localtime.tm_mon + 1,
47-
localtime.tm_mday,
48-
localtime.tm_hour,
49-
localtime.tm_min,
50-
localtime.tm_sec,
51-
0);
52-
53-
auto utc = pybind11::module::import("datetime").attr("timezone").attr("utc");
54-
using namespace pybind11::literals;
55-
return pydate.attr("replace")("tzinfo"_a=utc).inc_ref();
45+
localtime.tm_mon + 1,
46+
localtime.tm_mday,
47+
localtime.tm_hour,
48+
localtime.tm_min,
49+
localtime.tm_sec,
50+
0);
51+
52+
static auto utc = module::import("datetime").attr("timezone").attr("utc");
53+
using namespace literals;
54+
handle with_utc = pydate.attr("replace")("tzinfo"_a=utc).inc_ref();
55+
pydate.dec_ref();
56+
return with_utc;
5657
}
5758

5859
PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));

0 commit comments

Comments
 (0)