Skip to main content

Module time

Module time 

Source
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.28.0", 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<()> {
    Python::initialize();
    Python::attach(|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(())
    })
}