chrono.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
  3. Copyright (c) 2016 Trent Houliston <trent@houliston.me> and
  4. Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "pybind11.h"
  10. #include <chrono>
  11. #include <cmath>
  12. #include <ctime>
  13. #include <datetime.h>
  14. #include <mutex>
  15. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  16. PYBIND11_NAMESPACE_BEGIN(detail)
  17. template <typename type>
  18. class duration_caster {
  19. public:
  20. using rep = typename type::rep;
  21. using period = typename type::period;
  22. // signed 25 bits required by the standard.
  23. using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
  24. bool load(handle src, bool) {
  25. using namespace std::chrono;
  26. // Lazy initialise the PyDateTime import
  27. if (!PyDateTimeAPI) {
  28. PyDateTime_IMPORT;
  29. }
  30. if (!src) {
  31. return false;
  32. }
  33. // If invoked with datetime.delta object
  34. if (PyDelta_Check(src.ptr())) {
  35. value = type(duration_cast<duration<rep, period>>(
  36. days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
  37. + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
  38. + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
  39. return true;
  40. }
  41. // If invoked with a float we assume it is seconds and convert
  42. if (PyFloat_Check(src.ptr())) {
  43. value = type(duration_cast<duration<rep, period>>(
  44. duration<double>(PyFloat_AsDouble(src.ptr()))));
  45. return true;
  46. }
  47. return false;
  48. }
  49. // If this is a duration just return it back
  50. static const std::chrono::duration<rep, period> &
  51. get_duration(const std::chrono::duration<rep, period> &src) {
  52. return src;
  53. }
  54. // If this is a time_point get the time_since_epoch
  55. template <typename Clock>
  56. static std::chrono::duration<rep, period>
  57. get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
  58. return src.time_since_epoch();
  59. }
  60. static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
  61. using namespace std::chrono;
  62. // Use overloaded function to get our duration from our source
  63. // Works out if it is a duration or time_point and get the duration
  64. auto d = get_duration(src);
  65. // Lazy initialise the PyDateTime import
  66. if (!PyDateTimeAPI) {
  67. PyDateTime_IMPORT;
  68. }
  69. // Declare these special duration types so the conversions happen with the correct
  70. // primitive types (int)
  71. using dd_t = duration<int, std::ratio<86400>>;
  72. using ss_t = duration<int, std::ratio<1>>;
  73. using us_t = duration<int, std::micro>;
  74. auto dd = duration_cast<dd_t>(d);
  75. auto subd = d - dd;
  76. auto ss = duration_cast<ss_t>(subd);
  77. auto us = duration_cast<us_t>(subd - ss);
  78. return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
  79. }
  80. PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
  81. };
  82. inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
  83. #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
  84. if (localtime_s(buf, time))
  85. return nullptr;
  86. return buf;
  87. #else
  88. static std::mutex mtx;
  89. std::lock_guard<std::mutex> lock(mtx);
  90. std::tm *tm_ptr = std::localtime(time);
  91. if (tm_ptr != nullptr) {
  92. *buf = *tm_ptr;
  93. }
  94. return tm_ptr;
  95. #endif
  96. }
  97. // This is for casting times on the system clock into datetime.datetime instances
  98. template <typename Duration>
  99. class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  100. public:
  101. using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
  102. bool load(handle src, bool) {
  103. using namespace std::chrono;
  104. // Lazy initialise the PyDateTime import
  105. if (!PyDateTimeAPI) {
  106. PyDateTime_IMPORT;
  107. }
  108. if (!src) {
  109. return false;
  110. }
  111. std::tm cal;
  112. microseconds msecs;
  113. if (PyDateTime_Check(src.ptr())) {
  114. cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
  115. cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
  116. cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
  117. cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
  118. cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
  119. cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
  120. cal.tm_isdst = -1;
  121. msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
  122. } else if (PyDate_Check(src.ptr())) {
  123. cal.tm_sec = 0;
  124. cal.tm_min = 0;
  125. cal.tm_hour = 0;
  126. cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
  127. cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
  128. cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
  129. cal.tm_isdst = -1;
  130. msecs = microseconds(0);
  131. } else if (PyTime_Check(src.ptr())) {
  132. cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
  133. cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
  134. cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
  135. cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
  136. cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
  137. cal.tm_year = 70; // earliest available date for Python's datetime
  138. cal.tm_isdst = -1;
  139. msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
  140. } else {
  141. return false;
  142. }
  143. value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
  144. return true;
  145. }
  146. static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
  147. return_value_policy /* policy */,
  148. handle /* parent */) {
  149. using namespace std::chrono;
  150. // Lazy initialise the PyDateTime import
  151. if (!PyDateTimeAPI) {
  152. PyDateTime_IMPORT;
  153. }
  154. // Get out microseconds, and make sure they are positive, to avoid bug in eastern
  155. // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
  156. using us_t = duration<int, std::micro>;
  157. auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
  158. if (us.count() < 0) {
  159. us += seconds(1);
  160. }
  161. // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
  162. // > If std::time_t has lower precision, it is implementation-defined whether the value is
  163. // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
  164. std::time_t tt
  165. = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
  166. std::tm localtime;
  167. std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
  168. if (!localtime_ptr) {
  169. throw cast_error("Unable to represent system_clock in local time");
  170. }
  171. return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
  172. localtime.tm_mon + 1,
  173. localtime.tm_mday,
  174. localtime.tm_hour,
  175. localtime.tm_min,
  176. localtime.tm_sec,
  177. us.count());
  178. }
  179. PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
  180. };
  181. // Other clocks that are not the system clock are not measured as datetime.datetime objects
  182. // since they are not measured on calendar time. So instead we just make them timedeltas
  183. // Or if they have passed us a time as a float we convert that
  184. template <typename Clock, typename Duration>
  185. class type_caster<std::chrono::time_point<Clock, Duration>>
  186. : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
  187. template <typename Rep, typename Period>
  188. class type_caster<std::chrono::duration<Rep, Period>>
  189. : public duration_caster<std::chrono::duration<Rep, Period>> {};
  190. PYBIND11_NAMESPACE_END(detail)
  191. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)