Extract any Python datetime into some chrono type with abi3 feature enabled #4019
-
Hi everyone. First of all, I highly appreciate that version 0.21 allows me to extract Python datetimes into Rust chrono types even if some abi3 feature is enabled! I needed ugly workarounds before... If I am not mistaken however, there seems to be no single chrono type which can be extracted from every Python datetime. For example, In order to get any Python datetime into the Rust world, I am currently using this helper function: fn extract_dt(obj: &Bound<PyAny>) -> Option<DateTime<Utc>> {
if let Ok(dt) = obj.extract::<DateTime<FixedOffset>>() {
return Some(dt.to_utc());
}
if let Ok(dt) = obj.extract::<NaiveDateTime>() {
return Some(dt.and_local_timezone(Local).single()?.to_utc());
}
None
} Is this what I am supposed to do or is there an easier way? Is my helper function correct, and does it actually work for any possible Python datetime object? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hello, good question. I think the problem with automatic conversion of naive to timezone-aware date times is that it's quite common for users to not think hard about what their naive datetime means. I think you're right in the code above that it's now typically treated as local but it feels like this is still a space where it's easy to introduce a footgun. The code you wrote above looks correct. You could package this up into a newtype and implement |
Beta Was this translation helpful? Give feedback.
Hello, good question.
I think the problem with automatic conversion of naive to timezone-aware date times is that it's quite common for users to not think hard about what their naive datetime means. I think you're right in the code above that it's now typically treated as local but it feels like this is still a space where it's easy to introduce a footgun.
The code you wrote above looks correct. You could package this up into a newtype and implement
FromPyObject
for that type (or use#[pyo3(from_py_with = "extract_dt")]
to avoid needing to take&Bound<'_, PyAny>
as your function argument.