1use crate::conversion::IntoPyObject;
2#[cfg(wip_feature_std)]
3use crate::exceptions::PyOverflowError;
4use crate::exceptions::PyValueError;
5#[cfg(feature = "experimental-inspect")]
6use crate::inspect::PyStaticExpr;
7#[cfg(wip_feature_std)]
8use crate::sync::PyOnceLock;
9#[cfg(feature = "experimental-inspect")]
10use crate::type_object::PyTypeInfo;
11use crate::types::PyDelta;
12use crate::types::PyDeltaAccess;
13#[cfg(wip_feature_std)]
14use crate::types::any::PyAnyMethods;
15#[cfg(wip_feature_std)]
16use crate::types::{PyDateTime, PyTzInfo};
17use crate::{Borrowed, Bound, FromPyObject, PyAny, PyErr, Python};
18#[cfg(wip_feature_std)]
19use crate::{Py, PyResult};
20use core::time::Duration;
21#[cfg(wip_feature_std)]
22use std::time::{SystemTime, UNIX_EPOCH};
23
24const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
25
26impl FromPyObject<'_, '_> for Duration {
27 type Error = PyErr;
28
29 #[cfg(feature = "experimental-inspect")]
30 const INPUT_TYPE: PyStaticExpr = PyDelta::TYPE_HINT;
31
32 fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
33 let delta = obj.cast::<PyDelta>()?;
34
35 let days = u64::try_from(delta.get_days()).map_err(|_| {
37 PyValueError::new_err(
38 "It is not possible to convert a negative timedelta to a Rust Duration",
39 )
40 })?;
41 let seconds = u64::try_from(delta.get_seconds()).unwrap(); let microseconds = u32::try_from(delta.get_microseconds()).unwrap(); let total_seconds = days * SECONDS_PER_DAY + seconds; let nanoseconds = microseconds.checked_mul(1_000).unwrap(); Ok(Duration::new(total_seconds, nanoseconds))
49 }
50}
51
52impl<'py> IntoPyObject<'py> for Duration {
53 type Target = PyDelta;
54 type Output = Bound<'py, Self::Target>;
55 type Error = PyErr;
56
57 #[cfg(feature = "experimental-inspect")]
58 const OUTPUT_TYPE: PyStaticExpr = PyDelta::TYPE_HINT;
59
60 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
61 let days = self.as_secs() / SECONDS_PER_DAY;
62 let seconds = self.as_secs() % SECONDS_PER_DAY;
63 let microseconds = self.subsec_micros();
64
65 PyDelta::new(
66 py,
67 days.try_into()?,
68 seconds.try_into()?,
69 microseconds.try_into()?,
70 false,
71 )
72 }
73}
74
75impl<'py> IntoPyObject<'py> for &Duration {
76 type Target = PyDelta;
77 type Output = Bound<'py, Self::Target>;
78 type Error = PyErr;
79
80 #[cfg(feature = "experimental-inspect")]
81 const OUTPUT_TYPE: PyStaticExpr = Duration::OUTPUT_TYPE;
82
83 #[inline]
84 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
85 (*self).into_pyobject(py)
86 }
87}
88
89#[cfg(wip_feature_std)]
96impl FromPyObject<'_, '_> for SystemTime {
97 type Error = PyErr;
98
99 #[cfg(feature = "experimental-inspect")]
100 const INPUT_TYPE: PyStaticExpr = PyDateTime::TYPE_HINT;
101
102 fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
103 let duration_since_unix_epoch: Duration = obj.sub(unix_epoch_py(obj.py())?)?.extract()?;
104 UNIX_EPOCH
105 .checked_add(duration_since_unix_epoch)
106 .ok_or_else(|| {
107 PyOverflowError::new_err("Overflow error when converting the time to Rust")
108 })
109 }
110}
111
112#[cfg(wip_feature_std)]
113impl<'py> IntoPyObject<'py> for SystemTime {
114 type Target = PyDateTime;
115 type Output = Bound<'py, Self::Target>;
116 type Error = PyErr;
117
118 #[cfg(feature = "experimental-inspect")]
119 const OUTPUT_TYPE: PyStaticExpr = PyDateTime::TYPE_HINT;
120
121 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
122 let duration_since_unix_epoch =
123 self.duration_since(UNIX_EPOCH).unwrap().into_pyobject(py)?;
124 unix_epoch_py(py)?
125 .add(duration_since_unix_epoch)?
126 .cast_into()
127 .map_err(Into::into)
128 }
129}
130
131#[cfg(wip_feature_std)]
132impl<'py> IntoPyObject<'py> for &SystemTime {
133 type Target = PyDateTime;
134 type Output = Bound<'py, Self::Target>;
135 type Error = PyErr;
136
137 #[cfg(feature = "experimental-inspect")]
138 const OUTPUT_TYPE: PyStaticExpr = SystemTime::OUTPUT_TYPE;
139
140 #[inline]
141 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
142 (*self).into_pyobject(py)
143 }
144}
145
146#[cfg(wip_feature_std)]
147fn unix_epoch_py(py: Python<'_>) -> PyResult<Borrowed<'_, '_, PyDateTime>> {
148 static UNIX_EPOCH: PyOnceLock<Py<PyDateTime>> = PyOnceLock::new();
149 Ok(UNIX_EPOCH
150 .get_or_try_init(py, || {
151 let utc = PyTzInfo::utc(py)?;
152 Ok::<_, PyErr>(PyDateTime::new(py, 1970, 1, 1, 0, 0, 0, 0, Some(&utc))?.into())
153 })?
154 .bind_borrowed(py))
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 #[allow(unused_imports)]
161 use crate::platform::prelude::*;
162 #[cfg(wip_feature_std)]
163 use crate::types::PyDict;
164
165 #[test]
166 #[cfg(wip_feature_std)]
167 fn test_duration_frompyobject() {
168 Python::attach(|py| {
169 assert_eq!(
170 new_timedelta(py, 0, 0, 0).extract::<Duration>().unwrap(),
171 Duration::new(0, 0)
172 );
173 assert_eq!(
174 new_timedelta(py, 1, 0, 0).extract::<Duration>().unwrap(),
175 Duration::new(86400, 0)
176 );
177 assert_eq!(
178 new_timedelta(py, 0, 1, 0).extract::<Duration>().unwrap(),
179 Duration::new(1, 0)
180 );
181 assert_eq!(
182 new_timedelta(py, 0, 0, 1).extract::<Duration>().unwrap(),
183 Duration::new(0, 1_000)
184 );
185 assert_eq!(
186 new_timedelta(py, 1, 1, 1).extract::<Duration>().unwrap(),
187 Duration::new(86401, 1_000)
188 );
189 assert_eq!(
190 timedelta_class(py)
191 .getattr("max")
192 .unwrap()
193 .extract::<Duration>()
194 .unwrap(),
195 Duration::new(86399999999999, 999999000)
196 );
197 });
198 }
199
200 #[test]
201 #[cfg(wip_feature_std)]
202 fn test_duration_frompyobject_negative() {
203 Python::attach(|py| {
204 assert_eq!(
205 new_timedelta(py, 0, -1, 0)
206 .extract::<Duration>()
207 .unwrap_err()
208 .to_string(),
209 "ValueError: It is not possible to convert a negative timedelta to a Rust Duration"
210 );
211 })
212 }
213
214 #[test]
215 #[cfg(wip_feature_std)]
216 fn test_duration_into_pyobject() {
217 Python::attach(|py| {
218 let assert_eq = |l: Bound<'_, PyAny>, r: Bound<'_, PyAny>| {
219 assert!(l.eq(r).unwrap());
220 };
221
222 assert_eq(
223 Duration::new(0, 0).into_pyobject(py).unwrap().into_any(),
224 new_timedelta(py, 0, 0, 0),
225 );
226 assert_eq(
227 Duration::new(86400, 0)
228 .into_pyobject(py)
229 .unwrap()
230 .into_any(),
231 new_timedelta(py, 1, 0, 0),
232 );
233 assert_eq(
234 Duration::new(1, 0).into_pyobject(py).unwrap().into_any(),
235 new_timedelta(py, 0, 1, 0),
236 );
237 assert_eq(
238 Duration::new(0, 1_000)
239 .into_pyobject(py)
240 .unwrap()
241 .into_any(),
242 new_timedelta(py, 0, 0, 1),
243 );
244 assert_eq(
245 Duration::new(0, 1).into_pyobject(py).unwrap().into_any(),
246 new_timedelta(py, 0, 0, 0),
247 );
248 assert_eq(
249 Duration::new(86401, 1_000)
250 .into_pyobject(py)
251 .unwrap()
252 .into_any(),
253 new_timedelta(py, 1, 1, 1),
254 );
255 assert_eq(
256 Duration::new(86399999999999, 999999000)
257 .into_pyobject(py)
258 .unwrap()
259 .into_any(),
260 timedelta_class(py).getattr("max").unwrap(),
261 );
262 });
263 }
264
265 #[test]
266 fn test_duration_into_pyobject_overflow() {
267 Python::attach(|py| {
268 assert!(Duration::MAX.into_pyobject(py).is_err());
269 })
270 }
271
272 #[test]
273 #[cfg(wip_feature_std)]
274 fn test_time_frompyobject() {
275 Python::attach(|py| {
276 assert_eq!(
277 new_datetime(py, 1970, 1, 1, 0, 0, 0, 0)
278 .extract::<SystemTime>()
279 .unwrap(),
280 UNIX_EPOCH
281 );
282 assert_eq!(
283 new_datetime(py, 2020, 2, 3, 4, 5, 6, 7)
284 .extract::<SystemTime>()
285 .unwrap(),
286 UNIX_EPOCH
287 .checked_add(Duration::new(1580702706, 7000))
288 .unwrap()
289 );
290 assert_eq!(
291 max_datetime(py).extract::<SystemTime>().unwrap(),
292 UNIX_EPOCH
293 .checked_add(Duration::new(253402300799, 999999000))
294 .unwrap()
295 );
296 });
297 }
298
299 #[test]
300 #[cfg(wip_feature_std)]
301 fn test_time_frompyobject_before_epoch() {
302 Python::attach(|py| {
303 assert_eq!(
304 new_datetime(py, 1950, 1, 1, 0, 0, 0, 0)
305 .extract::<SystemTime>()
306 .unwrap_err()
307 .to_string(),
308 "ValueError: It is not possible to convert a negative timedelta to a Rust Duration"
309 );
310 })
311 }
312
313 #[test]
314 #[cfg(wip_feature_std)]
315 fn test_time_intopyobject() {
316 Python::attach(|py| {
317 let assert_eq = |l: Bound<'_, PyDateTime>, r: Bound<'_, PyDateTime>| {
318 assert!(l.eq(r).unwrap());
319 };
320
321 assert_eq(
322 UNIX_EPOCH
323 .checked_add(Duration::new(1580702706, 7123))
324 .unwrap()
325 .into_pyobject(py)
326 .unwrap(),
327 new_datetime(py, 2020, 2, 3, 4, 5, 6, 7),
328 );
329 assert_eq(
330 UNIX_EPOCH
331 .checked_add(Duration::new(253402300799, 999999000))
332 .unwrap()
333 .into_pyobject(py)
334 .unwrap(),
335 max_datetime(py),
336 );
337 });
338 }
339
340 #[cfg(wip_feature_std)]
341 #[expect(clippy::too_many_arguments)]
342 fn new_datetime(
343 py: Python<'_>,
344 year: i32,
345 month: u8,
346 day: u8,
347 hour: u8,
348 minute: u8,
349 second: u8,
350 microsecond: u32,
351 ) -> Bound<'_, PyDateTime> {
352 let utc = PyTzInfo::utc(py).unwrap();
353 PyDateTime::new(
354 py,
355 year,
356 month,
357 day,
358 hour,
359 minute,
360 second,
361 microsecond,
362 Some(&utc),
363 )
364 .unwrap()
365 }
366
367 #[cfg(wip_feature_std)]
368 fn max_datetime(py: Python<'_>) -> Bound<'_, PyDateTime> {
369 let naive_max = datetime_class(py).getattr("max").unwrap();
370 let kargs = PyDict::new(py);
371 kargs
372 .set_item("tzinfo", PyTzInfo::utc(py).unwrap())
373 .unwrap();
374 naive_max
375 .call_method("replace", (), Some(&kargs))
376 .unwrap()
377 .cast_into()
378 .unwrap()
379 }
380
381 #[test]
382 #[cfg(wip_feature_std)]
383 fn test_time_intopyobject_overflow() {
384 let big_system_time = UNIX_EPOCH
385 .checked_add(Duration::new(300000000000, 0))
386 .unwrap();
387 Python::attach(|py| {
388 assert!(big_system_time.into_pyobject(py).is_err());
389 })
390 }
391
392 #[cfg(wip_feature_std)]
393 fn new_timedelta(
394 py: Python<'_>,
395 days: i32,
396 seconds: i32,
397 microseconds: i32,
398 ) -> Bound<'_, PyAny> {
399 timedelta_class(py)
400 .call1((days, seconds, microseconds))
401 .unwrap()
402 }
403
404 #[cfg(wip_feature_std)]
405 fn datetime_class(py: Python<'_>) -> Bound<'_, PyAny> {
406 py.import("datetime").unwrap().getattr("datetime").unwrap()
407 }
408
409 #[cfg(wip_feature_std)]
410 fn timedelta_class(py: Python<'_>) -> Bound<'_, PyAny> {
411 py.import("datetime").unwrap().getattr("timedelta").unwrap()
412 }
413}