Skip to content

Commit 02064e8

Browse files
committed
make Timestamp casting thread-safe
Avoid gmtime and use Python's own methos instead.
1 parent 24ea43a commit 02064e8

File tree

1 file changed

+3
-15
lines changed

1 file changed

+3
-15
lines changed

lib/cast.h

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@
22
*
33
* This file is part of pyosmium. (https://osmcode.org/pyosmium/)
44
*
5-
* Copyright (C) 2024 Sarah Hoffmann <[email protected]> and others.
5+
* Copyright (C) 2025 Sarah Hoffmann <[email protected]> and others.
66
* For a full list of authors see the git log.
77
*/
88
#ifndef PYOSMIUM_CAST_H
99
#define PYOSMIUM_CAST_H
1010

1111
#include <datetime.h>
12-
#include <chrono>
1312

1413
#include <pybind11/pybind11.h>
1514
#include <osmium/osm.hpp>
@@ -44,25 +43,14 @@ namespace pybind11 { namespace detail {
4443

4544
static handle cast(type const &src, return_value_policy, handle)
4645
{
47-
using namespace std::chrono;
4846
// Lazy initialise the PyDateTime import
4947
if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
5048

5149
std::time_t tt = src.seconds_since_epoch();
52-
std::tm localtime = *std::gmtime(&tt);
53-
handle pydate = PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
54-
localtime.tm_mon + 1,
55-
localtime.tm_mday,
56-
localtime.tm_hour,
57-
localtime.tm_min,
58-
localtime.tm_sec,
59-
0);
6050

6151
static auto utc = module::import("datetime").attr("timezone").attr("utc");
62-
using namespace literals;
63-
handle with_utc = pydate.attr("replace")("tzinfo"_a=utc).inc_ref();
64-
pydate.dec_ref();
65-
return with_utc;
52+
53+
return PyDateTime_FromTimestamp(pybind11::make_tuple(tt, utc).ptr());
6654
}
6755

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

0 commit comments

Comments
 (0)