chrono.h 8.7 KB

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