You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

162 lines
6.4 KiB

8 years ago
  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. NAMESPACE_BEGIN(pybind11)
  25. NAMESPACE_BEGIN(detail)
  26. template <typename type> class duration_caster {
  27. public:
  28. typedef typename type::rep rep;
  29. typedef typename type::period period;
  30. typedef std::chrono::duration<uint_fast32_t, std::ratio<86400>> days;
  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. typedef std::chrono::time_point<std::chrono::system_clock, Duration> type;
  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. if (PyDateTime_Check(src.ptr())) {
  88. std::tm cal;
  89. cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
  90. cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
  91. cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
  92. cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
  93. cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
  94. cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
  95. cal.tm_isdst = -1;
  96. value = system_clock::from_time_t(std::mktime(&cal)) + microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
  97. return true;
  98. }
  99. else return false;
  100. }
  101. static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src, return_value_policy /* policy */, handle /* parent */) {
  102. using namespace std::chrono;
  103. // Lazy initialise the PyDateTime import
  104. if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
  105. std::time_t tt = system_clock::to_time_t(src);
  106. // this function uses static memory so it's best to copy it out asap just in case
  107. // otherwise other code that is using localtime may break this (not just python code)
  108. std::tm localtime = *std::localtime(&tt);
  109. // Declare these special duration types so the conversions happen with the correct primitive types (int)
  110. using us_t = duration<int, std::micro>;
  111. return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
  112. localtime.tm_mon + 1,
  113. localtime.tm_mday,
  114. localtime.tm_hour,
  115. localtime.tm_min,
  116. localtime.tm_sec,
  117. (duration_cast<us_t>(src.time_since_epoch() % seconds(1))).count());
  118. }
  119. PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));
  120. };
  121. // Other clocks that are not the system clock are not measured as datetime.datetime objects
  122. // since they are not measured on calendar time. So instead we just make them timedeltas
  123. // Or if they have passed us a time as a float we convert that
  124. template <typename Clock, typename Duration> class type_caster<std::chrono::time_point<Clock, Duration>>
  125. : public duration_caster<std::chrono::time_point<Clock, Duration>> {
  126. };
  127. template <typename Rep, typename Period> class type_caster<std::chrono::duration<Rep, Period>>
  128. : public duration_caster<std::chrono::duration<Rep, Period>> {
  129. };
  130. NAMESPACE_END(detail)
  131. NAMESPACE_END(pybind11)