Module time

Source
Available on crate feature time only.
Expand description

Conversions to and from timeโ€™s Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcDateTime and UtcOffset.

ยงSetup

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

[dependencies]
time = "0.3"
pyo3 = { version = "0.25.0-dev", features = ["time"] }

Note that you must use compatible versions of time and PyO3. The required time version may vary based on the version of PyO3.

use time::{Duration, OffsetDateTime, PrimitiveDateTime, Date, Time, Month};
use pyo3::{Python, PyResult, IntoPyObject, types::PyAnyMethods};

fn main() -> PyResult<()> {
    pyo3::prepare_freethreaded_python();
    Python::with_gil(|py| {
        // Create a fixed date and time (2022-01-01 12:00:00 UTC)
        let date = Date::from_calendar_date(2022, Month::January, 1).unwrap();
        let time = Time::from_hms(12, 0, 0).unwrap();
        let primitive_dt = PrimitiveDateTime::new(date, time);

        // Convert to OffsetDateTime with UTC offset
        let datetime = primitive_dt.assume_utc();

        // Create a duration of 1 hour
        let duration = Duration::hours(1);

        // Convert to Python objects
        let py_datetime = datetime.into_pyobject(py)?;
        let py_timedelta = duration.into_pyobject(py)?;

        // Add the duration to the datetime in Python
        let py_result = py_datetime.add(py_timedelta)?;

        // Convert the result back to Rust
        let result: OffsetDateTime = py_result.extract()?;
        assert_eq!(result.hour(), 13);

        Ok(())
    })
}

Macrosยง

impl_into_py_for_ref ๐Ÿ”’
month_from_number ๐Ÿ”’

Constantsยง

SECONDS_PER_DAY ๐Ÿ”’

Functionsยง

extract_date_time ๐Ÿ”’
โš ๏ธ Internal Docs โš ๏ธ Not Public API ๐Ÿ‘‰ Official Docs Here