-
Notifications
You must be signed in to change notification settings - Fork 790
/
Copy pathchrono.rs
1553 lines (1409 loc) · 54.7 KB
/
chrono.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg(feature = "chrono")]
//! Conversions to and from [chrono](https://docs.rs/chrono/)’s `Duration`,
//! `NaiveDate`, `NaiveTime`, `DateTime<Tz>`, `FixedOffset`, and `Utc`.
//!
//! # Setup
//!
//! To use this feature, add this to your **`Cargo.toml`**:
//!
//! ```toml
//! [dependencies]
//! chrono = "0.4"
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"chrono\"] }")]
//! ```
//!
//! Note that you must use compatible versions of chrono and PyO3.
//! The required chrono version may vary based on the version of PyO3.
//!
//! # Example: Convert a `datetime.datetime` to chrono's `DateTime<Utc>`
//!
//! ```rust
//! use chrono::{DateTime, Duration, TimeZone, Utc};
//! use pyo3::{Python, PyResult, IntoPyObject, types::PyAnyMethods};
//!
//! fn main() -> PyResult<()> {
//! pyo3::prepare_freethreaded_python();
//! Python::with_gil(|py| {
//! // Build some chrono values
//! let chrono_datetime = Utc.with_ymd_and_hms(2022, 1, 1, 12, 0, 0).unwrap();
//! let chrono_duration = Duration::seconds(1);
//! // Convert them to Python
//! let py_datetime = chrono_datetime.into_pyobject(py)?;
//! let py_timedelta = chrono_duration.into_pyobject(py)?;
//! // Do an operation in Python
//! let py_sum = py_datetime.call_method1("__add__", (py_timedelta,))?;
//! // Convert back to Rust
//! let chrono_sum: DateTime<Utc> = py_sum.extract()?;
//! println!("DateTime<Utc>: {}", chrono_datetime);
//! Ok(())
//! })
//! }
//! ```
use crate::conversion::IntoPyObject;
use crate::exceptions::{PyTypeError, PyUserWarning, PyValueError};
#[cfg(Py_LIMITED_API)]
use crate::sync::GILOnceCell;
use crate::types::any::PyAnyMethods;
#[cfg(not(Py_LIMITED_API))]
use crate::types::datetime::timezone_from_offset;
use crate::types::PyNone;
#[cfg(not(Py_LIMITED_API))]
use crate::types::{
timezone_utc, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyTime, PyTimeAccess,
PyTzInfo, PyTzInfoAccess,
};
use crate::{ffi, Bound, FromPyObject, PyAny, PyErr, PyObject, PyResult, Python};
#[cfg(Py_LIMITED_API)]
use crate::{intern, DowncastError};
#[allow(deprecated)]
use crate::{IntoPy, ToPyObject};
use chrono::offset::{FixedOffset, Utc};
use chrono::{
DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Offset, TimeZone, Timelike,
};
#[allow(deprecated)]
impl ToPyObject for Duration {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Duration {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Duration {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDelta;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
// Total number of days
let days = self.num_days();
// Remainder of seconds
let secs_dur = self - Duration::days(days);
let secs = secs_dur.num_seconds();
// Fractional part of the microseconds
let micros = (secs_dur - Duration::seconds(secs_dur.num_seconds()))
.num_microseconds()
// This should never panic since we are just getting the fractional
// part of the total microseconds, which should never overflow.
.unwrap();
#[cfg(not(Py_LIMITED_API))]
{
// We do not need to check the days i64 to i32 cast from rust because
// python will panic with OverflowError.
// We pass true as the `normalize` parameter since we'd need to do several checks here to
// avoid that, and it shouldn't have a big performance impact.
// The seconds and microseconds cast should never overflow since it's at most the number of seconds per day
PyDelta::new(
py,
days.try_into().unwrap_or(i32::MAX),
secs.try_into()?,
micros.try_into()?,
true,
)
}
#[cfg(Py_LIMITED_API)]
{
DatetimeTypes::try_get(py)
.and_then(|dt| dt.timedelta.bind(py).call1((days, secs, micros)))
}
}
}
impl<'py> IntoPyObject<'py> for &Duration {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDelta;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for Duration {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Duration> {
// Python size are much lower than rust size so we do not need bound checks.
// 0 <= microseconds < 1000000
// 0 <= seconds < 3600*24
// -999999999 <= days <= 999999999
#[cfg(not(Py_LIMITED_API))]
let (days, seconds, microseconds) = {
let delta = ob.downcast::<PyDelta>()?;
(
delta.get_days().into(),
delta.get_seconds().into(),
delta.get_microseconds().into(),
)
};
#[cfg(Py_LIMITED_API)]
let (days, seconds, microseconds) = {
check_type(ob, &DatetimeTypes::get(ob.py()).timedelta, "PyDelta")?;
(
ob.getattr(intern!(ob.py(), "days"))?.extract()?,
ob.getattr(intern!(ob.py(), "seconds"))?.extract()?,
ob.getattr(intern!(ob.py(), "microseconds"))?.extract()?,
)
};
Ok(
Duration::days(days)
+ Duration::seconds(seconds)
+ Duration::microseconds(microseconds),
)
}
}
#[allow(deprecated)]
impl ToPyObject for NaiveDate {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for NaiveDate {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for NaiveDate {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDate;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let DateArgs { year, month, day } = (&self).into();
#[cfg(not(Py_LIMITED_API))]
{
PyDate::new(py, year, month, day)
}
#[cfg(Py_LIMITED_API)]
{
DatetimeTypes::try_get(py).and_then(|dt| dt.date.bind(py).call1((year, month, day)))
}
}
}
impl<'py> IntoPyObject<'py> for &NaiveDate {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDate;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for NaiveDate {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<NaiveDate> {
#[cfg(not(Py_LIMITED_API))]
{
let date = ob.downcast::<PyDate>()?;
py_date_to_naive_date(date)
}
#[cfg(Py_LIMITED_API)]
{
check_type(ob, &DatetimeTypes::get(ob.py()).date, "PyDate")?;
py_date_to_naive_date(ob)
}
}
}
#[allow(deprecated)]
impl ToPyObject for NaiveTime {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for NaiveTime {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for NaiveTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&self).into();
#[cfg(not(Py_LIMITED_API))]
let time = PyTime::new(py, hour, min, sec, micro, None)?;
#[cfg(Py_LIMITED_API)]
let time = DatetimeTypes::try_get(py)
.and_then(|dt| dt.time.bind(py).call1((hour, min, sec, micro)))?;
if truncated_leap_second {
warn_truncated_leap_second(&time);
}
Ok(time)
}
}
impl<'py> IntoPyObject<'py> for &NaiveTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for NaiveTime {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<NaiveTime> {
#[cfg(not(Py_LIMITED_API))]
{
let time = ob.downcast::<PyTime>()?;
py_time_to_naive_time(time)
}
#[cfg(Py_LIMITED_API)]
{
check_type(ob, &DatetimeTypes::get(ob.py()).time, "PyTime")?;
py_time_to_naive_time(ob)
}
}
}
#[allow(deprecated)]
impl ToPyObject for NaiveDateTime {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for NaiveDateTime {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for NaiveDateTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let DateArgs { year, month, day } = (&self.date()).into();
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&self.time()).into();
#[cfg(not(Py_LIMITED_API))]
let datetime = PyDateTime::new(py, year, month, day, hour, min, sec, micro, None)?;
#[cfg(Py_LIMITED_API)]
let datetime = DatetimeTypes::try_get(py).and_then(|dt| {
dt.datetime
.bind(py)
.call1((year, month, day, hour, min, sec, micro))
})?;
if truncated_leap_second {
warn_truncated_leap_second(&datetime);
}
Ok(datetime)
}
}
impl<'py> IntoPyObject<'py> for &NaiveDateTime {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for NaiveDateTime {
fn extract_bound(dt: &Bound<'_, PyAny>) -> PyResult<NaiveDateTime> {
#[cfg(not(Py_LIMITED_API))]
let dt = dt.downcast::<PyDateTime>()?;
#[cfg(Py_LIMITED_API)]
check_type(dt, &DatetimeTypes::get(dt.py()).datetime, "PyDateTime")?;
// If the user tries to convert a timezone aware datetime into a naive one,
// we return a hard error. We could silently remove tzinfo, or assume local timezone
// and do a conversion, but better leave this decision to the user of the library.
#[cfg(not(Py_LIMITED_API))]
let has_tzinfo = dt.get_tzinfo().is_some();
#[cfg(Py_LIMITED_API)]
let has_tzinfo = !dt.getattr(intern!(dt.py(), "tzinfo"))?.is_none();
if has_tzinfo {
return Err(PyTypeError::new_err("expected a datetime without tzinfo"));
}
let dt = NaiveDateTime::new(py_date_to_naive_date(dt)?, py_time_to_naive_time(dt)?);
Ok(dt)
}
}
#[allow(deprecated)]
impl<Tz: TimeZone> ToPyObject for DateTime<Tz> {
fn to_object(&self, py: Python<'_>) -> PyObject {
// FIXME: convert to better timezone representation here than just convert to fixed offset
// See https://github.com/PyO3/pyo3/issues/3266
let tz = self.offset().fix().to_object(py);
let tz = tz.bind(py).downcast().unwrap();
naive_datetime_to_py_datetime(py, &self.naive_local(), Some(tz))
}
}
#[allow(deprecated)]
impl<Tz: TimeZone> IntoPy<PyObject> for DateTime<Tz> {
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py, Tz: TimeZone> IntoPyObject<'py> for DateTime<Tz> {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(&self).into_pyobject(py)
}
}
impl<'py, Tz: TimeZone> IntoPyObject<'py> for &DateTime<Tz> {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyDateTime;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let tz = self.offset().fix().into_pyobject(py)?;
let DateArgs { year, month, day } = (&self.naive_local().date()).into();
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&self.naive_local().time()).into();
#[cfg(not(Py_LIMITED_API))]
let datetime = PyDateTime::new(py, year, month, day, hour, min, sec, micro, Some(&tz))?;
#[cfg(Py_LIMITED_API)]
let datetime = DatetimeTypes::try_get(py).and_then(|dt| {
dt.datetime
.bind(py)
.call1((year, month, day, hour, min, sec, micro, tz))
})?;
if truncated_leap_second {
warn_truncated_leap_second(&datetime);
}
Ok(datetime)
}
}
impl<Tz: TimeZone + for<'py> FromPyObject<'py>> FromPyObject<'_> for DateTime<Tz> {
fn extract_bound(dt: &Bound<'_, PyAny>) -> PyResult<DateTime<Tz>> {
#[cfg(not(Py_LIMITED_API))]
let dt = dt.downcast::<PyDateTime>()?;
#[cfg(Py_LIMITED_API)]
check_type(dt, &DatetimeTypes::get(dt.py()).datetime, "PyDateTime")?;
#[cfg(not(Py_LIMITED_API))]
let tzinfo = dt.get_tzinfo();
#[cfg(Py_LIMITED_API)]
let tzinfo: Option<Bound<'_, PyAny>> = dt.getattr(intern!(dt.py(), "tzinfo"))?.extract()?;
let tz = if let Some(tzinfo) = tzinfo {
tzinfo.extract()?
} else {
return Err(PyTypeError::new_err(
"expected a datetime with non-None tzinfo",
));
};
let naive_dt = NaiveDateTime::new(py_date_to_naive_date(dt)?, py_time_to_naive_time(dt)?);
naive_dt.and_local_timezone(tz).single().ok_or_else(|| {
PyValueError::new_err(format!(
"The datetime {:?} contains an incompatible or ambiguous timezone",
dt
))
})
}
}
#[allow(deprecated)]
impl ToPyObject for FixedOffset {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for FixedOffset {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for FixedOffset {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let seconds_offset = self.local_minus_utc();
#[cfg(not(Py_LIMITED_API))]
{
let td = PyDelta::new(py, 0, seconds_offset, 0, true)?;
timezone_from_offset(&td)
}
#[cfg(Py_LIMITED_API)]
{
let td = Duration::seconds(seconds_offset.into()).into_pyobject(py)?;
DatetimeTypes::try_get(py).and_then(|dt| dt.timezone.bind(py).call1((td,)))
}
}
}
impl<'py> IntoPyObject<'py> for &FixedOffset {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for FixedOffset {
/// Convert python tzinfo to rust [`FixedOffset`].
///
/// Note that the conversion will result in precision lost in microseconds as chrono offset
/// does not supports microseconds.
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<FixedOffset> {
#[cfg(not(Py_LIMITED_API))]
let ob = ob.downcast::<PyTzInfo>()?;
#[cfg(Py_LIMITED_API)]
check_type(ob, &DatetimeTypes::get(ob.py()).tzinfo, "PyTzInfo")?;
// Passing Python's None to the `utcoffset` function will only
// work for timezones defined as fixed offsets in Python.
// Any other timezone would require a datetime as the parameter, and return
// None if the datetime is not provided.
// Trying to convert None to a PyDelta in the next line will then fail.
let py_timedelta = ob.call_method1("utcoffset", (PyNone::get(ob.py()),))?;
if py_timedelta.is_none() {
return Err(PyTypeError::new_err(format!(
"{:?} is not a fixed offset timezone",
ob
)));
}
let total_seconds: Duration = py_timedelta.extract()?;
// This cast is safe since the timedelta is limited to -24 hours and 24 hours.
let total_seconds = total_seconds.num_seconds() as i32;
FixedOffset::east_opt(total_seconds)
.ok_or_else(|| PyValueError::new_err("fixed offset out of bounds"))
}
}
#[allow(deprecated)]
impl ToPyObject for Utc {
#[inline]
fn to_object(&self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
#[allow(deprecated)]
impl IntoPy<PyObject> for Utc {
#[inline]
fn into_py(self, py: Python<'_>) -> PyObject {
self.into_pyobject(py).unwrap().into_any().unbind()
}
}
impl<'py> IntoPyObject<'py> for Utc {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
#[cfg(Py_LIMITED_API)]
{
Ok(timezone_utc(py).into_any())
}
#[cfg(not(Py_LIMITED_API))]
{
Ok(timezone_utc(py))
}
}
}
impl<'py> IntoPyObject<'py> for &Utc {
#[cfg(Py_LIMITED_API)]
type Target = PyAny;
#[cfg(not(Py_LIMITED_API))]
type Target = PyTzInfo;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
#[inline]
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
(*self).into_pyobject(py)
}
}
impl FromPyObject<'_> for Utc {
fn extract_bound(ob: &Bound<'_, PyAny>) -> PyResult<Utc> {
let py_utc = timezone_utc(ob.py());
if ob.eq(py_utc)? {
Ok(Utc)
} else {
Err(PyValueError::new_err("expected datetime.timezone.utc"))
}
}
}
struct DateArgs {
year: i32,
month: u8,
day: u8,
}
impl From<&NaiveDate> for DateArgs {
fn from(value: &NaiveDate) -> Self {
Self {
year: value.year(),
month: value.month() as u8,
day: value.day() as u8,
}
}
}
struct TimeArgs {
hour: u8,
min: u8,
sec: u8,
micro: u32,
truncated_leap_second: bool,
}
impl From<&NaiveTime> for TimeArgs {
fn from(value: &NaiveTime) -> Self {
let ns = value.nanosecond();
let checked_sub = ns.checked_sub(1_000_000_000);
let truncated_leap_second = checked_sub.is_some();
let micro = checked_sub.unwrap_or(ns) / 1000;
Self {
hour: value.hour() as u8,
min: value.minute() as u8,
sec: value.second() as u8,
micro,
truncated_leap_second,
}
}
}
fn naive_datetime_to_py_datetime(
py: Python<'_>,
naive_datetime: &NaiveDateTime,
#[cfg(not(Py_LIMITED_API))] tzinfo: Option<&Bound<'_, PyTzInfo>>,
#[cfg(Py_LIMITED_API)] tzinfo: Option<&Bound<'_, PyAny>>,
) -> PyObject {
let DateArgs { year, month, day } = (&naive_datetime.date()).into();
let TimeArgs {
hour,
min,
sec,
micro,
truncated_leap_second,
} = (&naive_datetime.time()).into();
#[cfg(not(Py_LIMITED_API))]
let datetime = PyDateTime::new(py, year, month, day, hour, min, sec, micro, tzinfo)
.expect("failed to construct datetime");
#[cfg(Py_LIMITED_API)]
let datetime = DatetimeTypes::get(py)
.datetime
.bind(py)
.call1((year, month, day, hour, min, sec, micro, tzinfo))
.expect("failed to construct datetime.datetime");
if truncated_leap_second {
warn_truncated_leap_second(&datetime);
}
datetime.into()
}
fn warn_truncated_leap_second(obj: &Bound<'_, PyAny>) {
let py = obj.py();
if let Err(e) = PyErr::warn(
py,
&py.get_type::<PyUserWarning>(),
ffi::c_str!("ignored leap-second, `datetime` does not support leap-seconds"),
0,
) {
e.write_unraisable(py, Some(obj))
};
}
#[cfg(not(Py_LIMITED_API))]
fn py_date_to_naive_date(py_date: &impl PyDateAccess) -> PyResult<NaiveDate> {
NaiveDate::from_ymd_opt(
py_date.get_year(),
py_date.get_month().into(),
py_date.get_day().into(),
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range date"))
}
#[cfg(Py_LIMITED_API)]
fn py_date_to_naive_date(py_date: &Bound<'_, PyAny>) -> PyResult<NaiveDate> {
NaiveDate::from_ymd_opt(
py_date.getattr(intern!(py_date.py(), "year"))?.extract()?,
py_date.getattr(intern!(py_date.py(), "month"))?.extract()?,
py_date.getattr(intern!(py_date.py(), "day"))?.extract()?,
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range date"))
}
#[cfg(not(Py_LIMITED_API))]
fn py_time_to_naive_time(py_time: &impl PyTimeAccess) -> PyResult<NaiveTime> {
NaiveTime::from_hms_micro_opt(
py_time.get_hour().into(),
py_time.get_minute().into(),
py_time.get_second().into(),
py_time.get_microsecond(),
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range time"))
}
#[cfg(Py_LIMITED_API)]
fn py_time_to_naive_time(py_time: &Bound<'_, PyAny>) -> PyResult<NaiveTime> {
NaiveTime::from_hms_micro_opt(
py_time.getattr(intern!(py_time.py(), "hour"))?.extract()?,
py_time
.getattr(intern!(py_time.py(), "minute"))?
.extract()?,
py_time
.getattr(intern!(py_time.py(), "second"))?
.extract()?,
py_time
.getattr(intern!(py_time.py(), "microsecond"))?
.extract()?,
)
.ok_or_else(|| PyValueError::new_err("invalid or out-of-range time"))
}
#[cfg(Py_LIMITED_API)]
fn check_type(value: &Bound<'_, PyAny>, t: &PyObject, type_name: &'static str) -> PyResult<()> {
if !value.is_instance(t.bind(value.py()))? {
return Err(DowncastError::new(value, type_name).into());
}
Ok(())
}
#[cfg(Py_LIMITED_API)]
struct DatetimeTypes {
date: PyObject,
datetime: PyObject,
time: PyObject,
timedelta: PyObject,
timezone: PyObject,
timezone_utc: PyObject,
tzinfo: PyObject,
}
#[cfg(Py_LIMITED_API)]
impl DatetimeTypes {
fn get(py: Python<'_>) -> &Self {
Self::try_get(py).expect("failed to load datetime module")
}
fn try_get(py: Python<'_>) -> PyResult<&Self> {
static TYPES: GILOnceCell<DatetimeTypes> = GILOnceCell::new();
TYPES.get_or_try_init(py, || {
let datetime = py.import("datetime")?;
let timezone = datetime.getattr("timezone")?;
Ok::<_, PyErr>(Self {
date: datetime.getattr("date")?.into(),
datetime: datetime.getattr("datetime")?.into(),
time: datetime.getattr("time")?.into(),
timedelta: datetime.getattr("timedelta")?.into(),
timezone_utc: timezone.getattr("utc")?.into(),
timezone: timezone.into(),
tzinfo: datetime.getattr("tzinfo")?.into(),
})
})
}
}
#[cfg(Py_LIMITED_API)]
fn timezone_utc(py: Python<'_>) -> Bound<'_, PyAny> {
DatetimeTypes::get(py).timezone_utc.bind(py).clone()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{types::PyTuple, BoundObject};
use std::{cmp::Ordering, panic};
#[test]
// Only Python>=3.9 has the zoneinfo package
// We skip the test on windows too since we'd need to install
// tzdata there to make this work.
#[cfg(all(Py_3_9, not(target_os = "windows")))]
fn test_zoneinfo_is_not_fixed_offset() {
use crate::ffi;
use crate::types::any::PyAnyMethods;
use crate::types::dict::PyDictMethods;
Python::with_gil(|py| {
let locals = crate::types::PyDict::new(py);
py.run(
ffi::c_str!("import zoneinfo; zi = zoneinfo.ZoneInfo('Europe/London')"),
None,
Some(&locals),
)
.unwrap();
let result: PyResult<FixedOffset> = locals.get_item("zi").unwrap().unwrap().extract();
assert!(result.is_err());
let res = result.err().unwrap();
// Also check the error message is what we expect
let msg = res.value(py).repr().unwrap().to_string();
assert_eq!(msg, "TypeError(\"zoneinfo.ZoneInfo(key='Europe/London') is not a fixed offset timezone\")");
});
}
#[test]
fn test_timezone_aware_to_naive_fails() {
// Test that if a user tries to convert a python's timezone aware datetime into a naive
// one, the conversion fails.
Python::with_gil(|py| {
let py_datetime =
new_py_datetime_ob(py, "datetime", (2022, 1, 1, 1, 0, 0, 0, python_utc(py)));
// Now test that converting a PyDateTime with tzinfo to a NaiveDateTime fails
let res: PyResult<NaiveDateTime> = py_datetime.extract();
assert_eq!(
res.unwrap_err().value(py).repr().unwrap().to_string(),
"TypeError('expected a datetime without tzinfo')"
);
});
}
#[test]
fn test_naive_to_timezone_aware_fails() {
// Test that if a user tries to convert a python's timezone aware datetime into a naive
// one, the conversion fails.
Python::with_gil(|py| {
let py_datetime = new_py_datetime_ob(py, "datetime", (2022, 1, 1, 1, 0, 0, 0));
// Now test that converting a PyDateTime with tzinfo to a NaiveDateTime fails
let res: PyResult<DateTime<Utc>> = py_datetime.extract();
assert_eq!(
res.unwrap_err().value(py).repr().unwrap().to_string(),
"TypeError('expected a datetime with non-None tzinfo')"
);
// Now test that converting a PyDateTime with tzinfo to a NaiveDateTime fails
let res: PyResult<DateTime<FixedOffset>> = py_datetime.extract();
assert_eq!(
res.unwrap_err().value(py).repr().unwrap().to_string(),
"TypeError('expected a datetime with non-None tzinfo')"
);
});
}
#[test]
fn test_invalid_types_fail() {
// Test that if a user tries to convert a python's timezone aware datetime into a naive
// one, the conversion fails.
Python::with_gil(|py| {
let none = py.None().into_bound(py);
assert_eq!(
none.extract::<Duration>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDelta'"
);
assert_eq!(
none.extract::<FixedOffset>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyTzInfo'"
);
assert_eq!(
none.extract::<Utc>().unwrap_err().to_string(),
"ValueError: expected datetime.timezone.utc"
);
assert_eq!(
none.extract::<NaiveTime>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyTime'"
);
assert_eq!(
none.extract::<NaiveDate>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDate'"
);
assert_eq!(
none.extract::<NaiveDateTime>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDateTime'"
);
assert_eq!(
none.extract::<DateTime<Utc>>().unwrap_err().to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDateTime'"
);
assert_eq!(
none.extract::<DateTime<FixedOffset>>()
.unwrap_err()
.to_string(),
"TypeError: 'NoneType' object cannot be converted to 'PyDateTime'"
);
});
}
#[test]
fn test_pyo3_timedelta_into_pyobject() {
// Utility function used to check different durations.
// The `name` parameter is used to identify the check in case of a failure.
let check = |name: &'static str, delta: Duration, py_days, py_seconds, py_ms| {
Python::with_gil(|py| {
let delta = delta.into_pyobject(py).unwrap();
let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms));
assert!(
delta.eq(&py_delta).unwrap(),
"{}: {} != {}",
name,
delta,
py_delta
);
});
};
let delta = Duration::days(-1) + Duration::seconds(1) + Duration::microseconds(-10);
check("delta normalization", delta, -1, 1, -10);
// Check the minimum value allowed by PyDelta, which is different
// from the minimum value allowed in Duration. This should pass.
let delta = Duration::seconds(-86399999913600); // min
check("delta min value", delta, -999999999, 0, 0);
// Same, for max value
let delta = Duration::seconds(86399999999999) + Duration::nanoseconds(999999000); // max
check("delta max value", delta, 999999999, 86399, 999999);
// Also check that trying to convert an out of bound value errors.
Python::with_gil(|py| {
assert!(Duration::min_value().into_pyobject(py).is_err());
assert!(Duration::max_value().into_pyobject(py).is_err());
});
}
#[test]
fn test_pyo3_timedelta_frompyobject() {
// Utility function used to check different durations.
// The `name` parameter is used to identify the check in case of a failure.
let check = |name: &'static str, delta: Duration, py_days, py_seconds, py_ms| {
Python::with_gil(|py| {
let py_delta = new_py_datetime_ob(py, "timedelta", (py_days, py_seconds, py_ms));
let py_delta: Duration = py_delta.extract().unwrap();
assert_eq!(py_delta, delta, "{}: {} != {}", name, py_delta, delta);
})
};
// Check the minimum value allowed by PyDelta, which is different
// from the minimum value allowed in Duration. This should pass.
check(
"min py_delta value",
Duration::seconds(-86399999913600),
-999999999,
0,
0,
);
// Same, for max value