Expand description
Conversions to and from chrono’s Duration
,
NaiveDate
, NaiveTime
, DateTime<Tz>
, FixedOffset
, and Utc
.
§Setup
To use this feature, add this to your Cargo.toml
:
[dependencies]
chrono = "0.4"
pyo3 = { version = "0.23.0-dev", 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>
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(())
})
}