polars_core/datatypes/temporal/
time_unit.rs1use crate::prelude::ArrowTimeUnit;
2
3#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Hash)]
4#[cfg_attr(
5 any(feature = "serde-lazy", feature = "serde"),
6 derive(serde::Serialize, serde::Deserialize)
7)]
8#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
9pub enum TimeUnit {
10 Nanoseconds,
11 Microseconds,
12 Milliseconds,
13}
14
15impl From<&ArrowTimeUnit> for TimeUnit {
16 fn from(tu: &ArrowTimeUnit) -> Self {
17 match tu {
18 ArrowTimeUnit::Nanosecond => TimeUnit::Nanoseconds,
19 ArrowTimeUnit::Microsecond => TimeUnit::Microseconds,
20 ArrowTimeUnit::Millisecond => TimeUnit::Milliseconds,
21 ArrowTimeUnit::Second => TimeUnit::Milliseconds,
23 }
24 }
25}
26
27impl std::fmt::Display for TimeUnit {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 match self {
30 TimeUnit::Nanoseconds => {
31 write!(f, "ns")
32 },
33 TimeUnit::Microseconds => {
34 write!(f, "μs")
35 },
36 TimeUnit::Milliseconds => {
37 write!(f, "ms")
38 },
39 }
40 }
41}
42
43impl TimeUnit {
44 pub fn to_ascii(self) -> &'static str {
45 use TimeUnit::*;
46 match self {
47 Nanoseconds => "ns",
48 Microseconds => "us",
49 Milliseconds => "ms",
50 }
51 }
52
53 pub fn to_arrow(self) -> ArrowTimeUnit {
54 match self {
55 TimeUnit::Nanoseconds => ArrowTimeUnit::Nanosecond,
56 TimeUnit::Microseconds => ArrowTimeUnit::Microsecond,
57 TimeUnit::Milliseconds => ArrowTimeUnit::Millisecond,
58 }
59 }
60}
61
62#[cfg(any(feature = "rows", feature = "object"))]
63#[cfg(any(feature = "dtype-datetime", feature = "dtype-duration"))]
64#[inline]
65pub fn convert_time_units<T>(v: T, tu_l: TimeUnit, tu_r: TimeUnit) -> T
66where
67 T: num_traits::Num + num_traits::NumCast,
68{
69 use TimeUnit::*;
70 match (tu_l, tu_r) {
71 (Nanoseconds, Microseconds) => v / T::from(1_000).unwrap(),
72 (Nanoseconds, Milliseconds) => v / T::from(1_000_000).unwrap(),
73 (Microseconds, Nanoseconds) => v * T::from(1_000).unwrap(),
74 (Microseconds, Milliseconds) => v / T::from(1_000).unwrap(),
75 (Milliseconds, Microseconds) => v * T::from(1_000).unwrap(),
76 (Milliseconds, Nanoseconds) => v * T::from(1_000_000).unwrap(),
77 _ => v,
78 }
79}