chrono.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 <cmath>
  11. #include <ctime>
  12. #include <chrono>
  13. #include <datetime.h>
  14. // Backport the PyDateTime_DELTA functions from Python3.3 if required
  15. #ifndef PyDateTime_DELTA_GET_DAYS
  16. #define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days)
  17. #endif
  18. #ifndef PyDateTime_DELTA_GET_SECONDS
  19. #define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds)
  20. #endif
  21. #ifndef PyDateTime_DELTA_GET_MICROSECONDS
  22. #define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta*)o)->microseconds)
  23. #endif
  24. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  25. PYBIND11_NAMESPACE_BEGIN(detail)
  26. template <typename type> class duration_caster {
  27. public:
  28. using rep = typename type::rep;
  29. using period = typename type::period;
  30. using days = std::chrono::duration<uint_fast32_t, std::ratio<86400>>;
  31. bool load(handle src, bool) {
  32. using namespace std::chrono;
  33. // Lazy initialise the PyDateTime import
  34. if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
  35. if (!src) return false;
  36. // If invoked with datetime.delta object
  37. if (PyDelta_Check(src.ptr())) {
  38. value = type(duration_cast<duration<rep, period>>(
  39. days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
  40. + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
  41. + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
  42. return true;
  43. }
  44. // If invoked with a float we assume it is seconds and convert
  45. else if (PyFloat_Check(src.ptr())) {
  46. value = type(duration_cast<duration<rep, period>>(duration<double>(PyFloat_AsDouble(src.ptr()))));
  47. return true;
  48. }
  49. else return false;
  50. }
  51. // If this is a duration just return it back
  52. static const std::chrono::duration<rep, period>& get_duration(const std::chrono::duration<rep, period> &src) {
  53. return src;
  54. }
  55. // If this is a time_point get the time_since_epoch
  56. template <typename Clock> static std::chrono::duration<rep, period> get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
  57. return src.time_since_epoch();
  58. }
  59. static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
  60. using namespace std::chrono;
  61. // Use overloaded function to get our duration from our source
  62. // Works out if it is a duration or time_point and get the duration
  63. auto d = get_duration(src);
  64. // Lazy initialise the PyDateTime import
  65. if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
  66. // Declare these special duration types so the conversions happen with the correct primitive types (int)
  67. using dd_t = duration<int, std::ratio<86400>>;
  68. using ss_t = duration<int, std::ratio<1>>;
  69. using us_t = duration<int, std::micro>;
  70. auto dd = duration_cast<dd_t>(d);
  71. auto subd = d - dd;
  72. auto ss = duration_cast<ss_t>(subd);
  73. auto us = duration_cast<us_t>(subd - ss);
  74. return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
  75. }
  76. PYBIND11_TYPE_CASTER(type, _("datetime.timedelta"));
  77. };
  78. // This is for casting times on the system clock into datetime.datetime instances
  79. template <typename Duration> class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  80. public:
  81. using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
  82. bool load(handle src, bool) {
  83. using namespace std::chrono;
  84. // Lazy initialise the PyDateTime import
  85. if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
  86. if (!src) return false;
  87. std::tm cal;
  88. microseconds msecs;
  89. if (PyDateTime_Check(src.ptr())) {
  90. cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
  91. cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
  92. cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
  93. cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
  94. cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
  95. cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
  96. cal.tm_isdst = -1;
  97. msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
  98. } else if (PyDate_Check(src.ptr())) {
  99. cal.tm_sec = 0;
  100. cal.tm_min = 0;
  101. cal.tm_hour = 0;
  102. cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
  103. cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
  104. cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
  105. cal.tm_isdst = -1;
  106. msecs = microseconds(0);
  107. } else if (PyTime_Check(src.ptr())) {
  108. cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
  109. cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
  110. cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
  111. cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
  112. cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
  113. cal.tm_year = 70; // earliest available date for Python's datetime
  114. cal.tm_isdst = -1;
  115. msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
  116. }
  117. else return false;
  118. value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
  119. return true;
  120. }
  121. static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src, return_value_policy /* policy */, handle /* parent */) {
  122. using namespace std::chrono;
  123. // Lazy initialise the PyDateTime import
  124. if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
  125. // Get out microseconds, and make sure they are positive, to avoid bug in eastern hemisphere time zones
  126. // (cfr. https://github.com/pybind/pybind11/issues/2417)
  127. using us_t = duration<int, std::micro>;
  128. auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
  129. if (us.count() < 0)
  130. us += seconds(1);
  131. // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
  132. // > If std::time_t has lower precision, it is implementation-defined whether the value is rounded or truncated.
  133. // (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
  134. std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
  135. // this function uses static memory so it's best to copy it out asap just in case
  136. // otherwise other code that is using localtime may break this (not just python code)
  137. std::tm localtime = *std::localtime(&tt);
  138. return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
  139. localtime.tm_mon + 1,
  140. localtime.tm_mday,
  141. localtime.tm_hour,
  142. localtime.tm_min,
  143. localtime.tm_sec,
  144. us.count());
  145. }
  146. PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));
  147. };
  148. // Other clocks that are not the system clock are not measured as datetime.datetime objects
  149. // since they are not measured on calendar time. So instead we just make them timedeltas
  150. // Or if they have passed us a time as a float we convert that
  151. template <typename Clock, typename Duration> class type_caster<std::chrono::time_point<Clock, Duration>>
  152. : public duration_caster<std::chrono::time_point<Clock, Duration>> {
  153. };
  154. template <typename Rep, typename Period> class type_caster<std::chrono::duration<Rep, Period>>
  155. : public duration_caster<std::chrono::duration<Rep, Period>> {
  156. };
  157. PYBIND11_NAMESPACE_END(detail)
  158. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)