mardi 25 janvier 2022

Why use time_t to convert between C++ and Python dates in pybind

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 of days, hours, ..., microseconds to the default.
  • Conversely, to convert from C++, I would do something like: convert the given time_point to year_month_day and then use arithmetic / truncation operations to get the hours ... 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 / local std::chrono::time_point<std::chrono::local_t, std::chrono::days> conversion, where I'm assuming that if the time_t based conversion is required for a date-time, it won't be required in this, simpler, case.

Aucun commentaire:

Enregistrer un commentaire