Module pyo3::chrono

source ·
Available on crate feature chrono and non-Py_LIMITED_API only.
Expand description

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

Unavailable with the abi3 feature.

Setup

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

[dependencies]
# change * to the latest versions
pyo3 = { version = "*", features = ["chrono"] }
chrono = "0.4"
pyo3 = { version = "0.18.1", 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 PyDateTime to chrono’s DateTime<Utc>

use chrono::{Utc, DateTime};
use pyo3::{Python, ToPyObject, types::PyDateTime};

fn main() {
    pyo3::prepare_freethreaded_python();
    Python::with_gil(|py| {
        // Create an UTC datetime in python
        let py_tz = Utc.to_object(py);
        let py_tz = py_tz.downcast(py).unwrap();
        let pydatetime = PyDateTime::new(py, 2022, 1, 1, 12, 0, 0, 0, Some(py_tz)).unwrap();
        println!("PyDateTime: {}", pydatetime);
        // Now convert it to chrono's DateTime<Utc>
        let chrono_datetime: DateTime<Utc> = pydatetime.extract().unwrap();
        println!("DateTime<Utc>: {}", chrono_datetime);
    });
}