Skip to main content

polars_core/chunked_array/temporal/
mod.rs

1//! Traits and utilities for temporal data.
2pub mod conversion;
3#[cfg(feature = "dtype-date")]
4mod date;
5#[cfg(feature = "dtype-datetime")]
6mod datetime;
7#[cfg(feature = "dtype-duration")]
8mod duration;
9#[cfg(feature = "timezones")]
10pub mod replace_time_zone;
11#[cfg(feature = "temporal")]
12pub mod string;
13#[cfg(feature = "dtype-time")]
14mod time;
15
16#[cfg(feature = "dtype-date")]
17use chrono::NaiveDate;
18use chrono::NaiveDateTime;
19#[cfg(any(feature = "dtype-time", feature = "dtype-date"))]
20use chrono::NaiveTime;
21#[cfg(feature = "timezones")]
22use chrono::TimeZone as _;
23#[cfg(feature = "timezones")]
24use chrono_tz::Tz;
25#[cfg(feature = "timezones")]
26use polars_arrow::legacy::kernels::{Ambiguous, NonExistent, convert_to_naive_local};
27#[cfg(feature = "timezones")]
28use polars_error::PolarsResult;
29#[cfg(feature = "timezones")]
30use polars_utils::pl_str::PlSmallStr;
31#[cfg(feature = "dtype-time")]
32pub use time::time_to_time64ns;
33
34pub use self::conversion::*;
35
36/// Localize datetime according to given time zone.
37///
38/// e.g. '2021-01-01 03:00' -> '2021-01-01 03:00CDT'
39///
40/// Note: this may only return `Ok(None)` if ambiguous is Ambiguous::Null
41/// or if non_existent is NonExistent::Null.
42/// Otherwise, it will either return `Ok(Some(NaiveDateTime))` or `PolarsError`.
43///
44/// Therefore, calling `try_localize_datetime(..., Ambiguous::Raise, NonExistent::Raise)?.unwrap()`
45/// is safe, and will never panic.
46#[cfg(feature = "timezones")]
47pub fn try_localize_datetime(
48    ndt: NaiveDateTime,
49    tz: &Tz,
50    ambiguous: Ambiguous,
51    non_existent: NonExistent,
52) -> PolarsResult<Option<NaiveDateTime>> {
53    convert_to_naive_local(&chrono_tz::UTC, tz, ndt, ambiguous, non_existent)
54}
55
56#[cfg(feature = "timezones")]
57pub fn unlocalize_datetime(ndt: NaiveDateTime, tz: &Tz) -> NaiveDateTime {
58    // e.g. '2021-01-01 03:00CDT' -> '2021-01-01 03:00'
59    tz.from_utc_datetime(&ndt).naive_local()
60}