pybind provides conversions between standard Python and C++ date types. These are implemented in the optional header file chrono.h. The second class, the template specialization of type_caster
, converts between Python datetime.datetime
and C++ std::chrono::time_point<std::chrono::system_clock, Duration>
, representing time since UTC for an arbitrary measure (Duration
can be days, microseconds, etc).
When converting to C++, a std::tm
is created, then system_clock::from_time_t(std::mktime(...))
is used. Conversely when converting from C++, localtime(system_clock::to_time_t(...))
is used.
If I were writing this function, I would use the C++ dates library directly:
- to convert to C++, I would do something like: return a
timepoint
by adding the appropriate number ofdays
,hours
, ...,microseconds
to the default. - Conversely, to convert from C++, I would do something like: convert the given
time_point
toyear_month_day
and then use arithmetic / truncation operations to get thehours
...microseconds
.
However, out of all the open source libraries I use, pybind is probably the one I admire the most, so I'm wondering what I'm missing? Why go via time_t?
More context:
- For high precision time points, I'm most interested in the
datetime.datetime
<=>std::chrono::time_point<std::chrono::system_clock, std::chrono::microseconds>
conversion, as I use this C++ type throughout my library. - For time points measured in days, I also intend to add a
date.date
<=> naive / localstd::chrono::time_point<std::chrono::local_t, std::chrono::days>
conversion, where I'm assuming that if thetime_t
based conversion is required for a date-time, it won't be required in this, simpler, case.
Aucun commentaire:
Enregistrer un commentaire