Module pyo3::chrono

source ·
Expand description

Conversions to and from chrono’s Duration, NaiveDate, NaiveTime, DateTime<Tz>, FixedOffset, and Utc.


To use this feature, add this to your Cargo.toml:

chrono = "0.4"
pyo3 = { version = "0.21.2", 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, ToPyObject};

fn main() {
    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.to_object(py);
        let py_timedelta = chrono_duration.to_object(py);
        // Do an operation in Python
        let py_sum = py_datetime.call_method1(py, "__add__", (py_timedelta,)).unwrap();
        // Convert back to Rust
        let chrono_sum: DateTime<Utc> = py_sum.extract(py).unwrap();
        println!("DateTime<Utc>: {}", chrono_datetime);