diff --git a/Cargo.lock b/Cargo.lock index b44847d..5a15162 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -990,15 +990,6 @@ dependencies = [ "libm", ] -[[package]] -name = "num_threads" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" -dependencies = [ - "libc", -] - [[package]] name = "object" version = "0.39.1" @@ -1705,9 +1696,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" dependencies = [ "deranged", - "libc", "num-conv", - "num_threads", "powerfmt", "serde_core", "time-core", diff --git a/Cargo.toml b/Cargo.toml index a75f3fb..2fad13b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,7 @@ polars-core = { version = "0.55.2", default-features = false, features = [ "dtype-decimal", ], optional = true } polars-arrow = { version = "0.55.2", optional = true } -time = { version = "0.3", optional = true, features = ["parsing", "formatting", "macros", "local-offset"] } +time = { version = "0.3", optional = true, features = ["parsing"] } phf = { version = "0.13.1", features = ["macros"], optional = true } num-traits = "0.2.19" rayon = { version = "1.11.0", optional = true } diff --git a/src/structs/field_array.rs b/src/structs/field_array.rs index 09ffac7..87750f3 100644 --- a/src/structs/field_array.rs +++ b/src/structs/field_array.rs @@ -569,9 +569,17 @@ fn format_field_array_with_timezone( field_array: &FieldArray, timezone: &str, ) -> std::fmt::Result { - use crate::traits::print::MAX_PREVIEW; + use crate::traits::print::{MAX_PREVIEW, format_datetime_value}; use crate::{Array, TemporalArray}; + // Time zone conversion requires the `time` crate. + if cfg!(not(feature = "datetime_ops")) { + panic!( + "Timezone functionality requires the 'datetime_ops' feature. \ + Enable it in Cargo.toml with: features = [\"datetime_ops\"]" + ); + } + let arr = &field_array.array; let len = arr.len(); let nulls = arr.null_count(); @@ -591,7 +599,7 @@ fn format_field_array_with_timezone( if i > 0 { write!(f, ", ")?; } - write!(f, "{}", format_datetime_with_tz(dt.as_ref(), i, timezone))?; + write!(f, "{}", format_datetime_value(dt.as_ref(), i))?; } if len > MAX_PREVIEW { write!(f, ", ...")?; @@ -612,7 +620,7 @@ fn format_field_array_with_timezone( if i > 0 { write!(f, ", ")?; } - write!(f, "{}", format_datetime_with_tz(dt.as_ref(), i, timezone))?; + write!(f, "{}", format_datetime_value(dt.as_ref(), i))?; } if len > MAX_PREVIEW { write!(f, ", ...")?; @@ -623,15 +631,6 @@ fn format_field_array_with_timezone( } } -#[cfg(feature = "datetime")] -fn format_datetime_with_tz(arr: &crate::DatetimeArray, idx: usize, timezone: &str) -> String -where - T: crate::Integer + std::fmt::Display, -{ - use crate::traits::print::format_datetime_value; - format_datetime_value(arr, idx, Some(timezone)) -} - impl Shape for FieldArray { fn shape(&self) -> ShapeDim { ShapeDim::Rank1(self.len()) diff --git a/src/structs/variants/datetime/mod.rs b/src/structs/variants/datetime/mod.rs index c4a5c70..a17a615 100644 --- a/src/structs/variants/datetime/mod.rs +++ b/src/structs/variants/datetime/mod.rs @@ -451,7 +451,7 @@ where T: Integer + Display, { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - use crate::traits::print::MAX_PREVIEW; + use crate::traits::print::{MAX_PREVIEW, format_datetime_value}; let len = self.len(); let nulls = self.null_count(); @@ -464,78 +464,11 @@ where )?; write!(f, "[")?; - - #[cfg(feature = "datetime_ops")] - { - use time::OffsetDateTime; - for i in 0..usize::min(len, MAX_PREVIEW) { - if i > 0 { - write!(f, ", ")?; - } - match self.value(i) { - Some(val) => match self.time_unit() { - TimeUnit::Seconds => { - let v = val.to_i64().unwrap(); - match OffsetDateTime::from_unix_timestamp(v) { - Ok(dt) => write!(f, "{}", dt), - Err(_) => write!(f, "{}s", val), - } - } - TimeUnit::Milliseconds => { - let v = val.to_i64().unwrap(); - match OffsetDateTime::from_unix_timestamp_nanos((v as i128) * 1_000_000) - { - Ok(dt) => write!(f, "{}", dt), - Err(_) => write!(f, "{}ms", val), - } - } - TimeUnit::Microseconds => { - let v = val.to_i64().unwrap(); - match OffsetDateTime::from_unix_timestamp_nanos((v as i128) * 1_000) { - Ok(dt) => write!(f, "{}", dt), - Err(_) => write!(f, "{}µs", val), - } - } - TimeUnit::Nanoseconds => { - let v = val.to_i64().unwrap(); - match OffsetDateTime::from_unix_timestamp_nanos(v as i128) { - Ok(dt) => write!(f, "{}", dt), - Err(_) => write!(f, "{}ns", val), - } - } - TimeUnit::Days => { - let days = val.to_i64().unwrap(); - match time::Date::from_julian_day((days + UNIX_EPOCH_JULIAN_DAY) as i32) - { - Ok(date) => write!(f, "{}", date), - Err(_) => write!(f, "{}d", val), - } - } - }, - None => write!(f, "null"), - }?; - } - } - - #[cfg(not(feature = "datetime_ops"))] - { - // Raw value plus suffix - let suffix = match self.time_unit() { - TimeUnit::Seconds => "s", - TimeUnit::Milliseconds => "ms", - TimeUnit::Microseconds => "µs", - TimeUnit::Nanoseconds => "ns", - TimeUnit::Days => "d", - }; - for i in 0..usize::min(len, MAX_PREVIEW) { - if i > 0 { - write!(f, ", ")?; - } - match self.value(i) { - Some(val) => write!(f, "{}{}", val, suffix)?, - None => write!(f, "null")?, - } + for i in 0..usize::min(len, MAX_PREVIEW) { + if i > 0 { + write!(f, ", ")?; } + write!(f, "{}", format_datetime_value(self, i))?; } if len > MAX_PREVIEW { diff --git a/src/traits/print.rs b/src/traits/print.rs index ae3cdbf..1064a0c 100644 --- a/src/traits/print.rs +++ b/src/traits/print.rs @@ -114,8 +114,8 @@ pub(crate) fn value_to_string(arr: &Array, idx: usize) -> String { // ------------------------- datetime ----------------------------- #[cfg(feature = "datetime")] Array::TemporalArray(inner) => match inner { - TemporalArray::Datetime32(dt) => format_datetime_value(dt, idx, None), - TemporalArray::Datetime64(dt) => format_datetime_value(dt, idx, None), + TemporalArray::Datetime32(dt) => format_datetime_value(dt, idx), + TemporalArray::Datetime64(dt) => format_datetime_value(dt, idx), TemporalArray::Null => "null".into(), }, // ------------------------- fallback ----------------------------- @@ -292,147 +292,106 @@ pub(crate) fn print_ndarray_body( } } +/// Formats the datetime value at `idx` according to the array's `Dt`. +/// +/// ## Behaviour +/// With `datetime_ops`: +/// - `Date32` and `Date64` print as `YYYY-MM-DD`. +/// - `Timestamp` prints as `YYYY-MM-DD HH:MM:SS`, followed by the fraction +/// digits of its time unit: 3 for milliseconds, 6 for microseconds and 9 for +/// nanoseconds. The values of an array therefore print at one width. +/// - Timestamps with a time zone print their UTC value followed by `+00:00`, +/// as in `2026-01-01 09:30:00+00:00`. +/// - `Time32` and `Time64` print the time of day as `HH:MM:SS`, with the +/// fraction digits of their time unit. +/// - `Duration32` and `Duration64` print the stored count with its time unit +/// suffix, as in `90s`. +/// +/// Without `datetime_ops`, and for dates and timestamps outside the `time` +/// crate's date range, the stored integer prints with its time unit suffix. +/// Nulls print as `null`. #[cfg(feature = "datetime")] -pub(crate) fn format_datetime_value( - arr: &DatetimeArray, - idx: usize, - timezone: Option<&str>, -) -> String +pub(crate) fn format_datetime_value(arr: &DatetimeArray, idx: usize) -> String where T: Integer + std::fmt::Display, { - use crate::MaskedArray; + use crate::{MaskedArray, TimeUnit}; if arr.is_null(idx) { return "null".into(); } #[cfg(feature = "datetime_ops")] { - use crate::TimeUnit; + use crate::Dt; use time::OffsetDateTime; - let utc_dt = match arr.time_unit() { - TimeUnit::Seconds => { - let secs = arr.data[idx].to_i64().unwrap(); - OffsetDateTime::from_unix_timestamp(secs).ok() - } - TimeUnit::Milliseconds => { - let v = arr.data[idx].to_i64().unwrap(); - OffsetDateTime::from_unix_timestamp_nanos((v as i128) * 1_000_000).ok() - } - TimeUnit::Microseconds => { - let v = arr.data[idx].to_i64().unwrap(); - OffsetDateTime::from_unix_timestamp_nanos((v as i128) * 1_000).ok() - } - TimeUnit::Nanoseconds => { - let v = arr.data[idx].to_i64().unwrap(); - OffsetDateTime::from_unix_timestamp_nanos(v as i128).ok() - } - TimeUnit::Days => { - use crate::structs::variants::datetime::UNIX_EPOCH_JULIAN_DAY; - let days = arr.data[idx].to_i64().unwrap(); - time::Date::from_julian_day((days + UNIX_EPOCH_JULIAN_DAY) as i32) - .ok() - .and_then(|d| d.with_hms(0, 0, 0).ok()) - .map(|dt| dt.assume_utc()) - } + let unit = arr.time_unit(); + let value = arr.data[idx].to_i64().unwrap(); + + // The time unit fixes the number of fraction digits. + let fraction = |nanosecond: u32| match unit { + TimeUnit::Milliseconds => format!(".{:03}", nanosecond / 1_000_000), + TimeUnit::Microseconds => format!(".{:06}", nanosecond / 1_000), + TimeUnit::Nanoseconds => format!(".{:09}", nanosecond), + TimeUnit::Seconds | TimeUnit::Days => String::new(), + }; + let format_date = |dt: OffsetDateTime| { + format!("{:04}-{:02}-{:02}", dt.year(), u8::from(dt.month()), dt.day()) }; - if let Some(dt) = utc_dt { - if let Some(tz) = timezone { - format_with_timezone(dt, tz) - } else { - dt.to_string() + match &arr.dtype { + Dt::Date32 | Dt::Date64 => { + // The conversion depends only on the time unit, and is shared with `DatetimeOps`. + if let Some(dt) = DatetimeArray::::i64_to_datetime(value, unit) { + return format_date(dt); + } } - } else { - let v = arr.data[idx]; - let suffix = match arr.time_unit() { - TimeUnit::Seconds => "s", - TimeUnit::Milliseconds => "ms", - TimeUnit::Microseconds => "µs", - TimeUnit::Nanoseconds => "ns", - TimeUnit::Days => "d", - }; - format!("{v}{suffix}") - } - } - #[cfg(not(feature = "datetime_ops"))] - { - use crate::TimeUnit; - - if timezone.is_some() { - panic!( - "Timezone functionality requires the 'datetime_ops' feature. \ - Enable it in Cargo.toml with: features = [\"datetime_ops\"]" - ); + Dt::Timestamp(_, tz) => { + if let Some(dt) = DatetimeArray::::i64_to_datetime(value, unit) { + // Timestamps are stored in UTC. Values with a time zone print + // that UTC value with its offset. + let offset = if tz.is_some() { "+00:00" } else { "" }; + return format!( + "{} {:02}:{:02}:{:02}{}{}", + format_date(dt), + dt.hour(), + dt.minute(), + dt.second(), + fraction(dt.nanosecond()), + offset + ); + } + } + Dt::Time32(_) | Dt::Time64(_) if value >= 0 && unit != TimeUnit::Days => { + let per_second: i64 = match unit { + TimeUnit::Milliseconds => 1_000, + TimeUnit::Microseconds => 1_000_000, + TimeUnit::Nanoseconds => 1_000_000_000, + TimeUnit::Seconds | TimeUnit::Days => 1, + }; + let seconds = value / per_second; + let nanosecond = (value % per_second * (1_000_000_000 / per_second)) as u32; + return format!( + "{:02}:{:02}:{:02}{}", + seconds / 3_600, + seconds / 60 % 60, + seconds % 60, + fraction(nanosecond) + ); + } + _ => {} } - - let v = arr.data[idx]; - let suffix = match arr.time_unit() { - TimeUnit::Seconds => "s", - TimeUnit::Milliseconds => "ms", - TimeUnit::Microseconds => "µs", - TimeUnit::Nanoseconds => "ns", - TimeUnit::Days => "d", - }; - format!("{v}{suffix}") } -} - -#[cfg(all(feature = "datetime", feature = "datetime_ops"))] -fn format_with_timezone(utc_dt: time::OffsetDateTime, tz: &str) -> String { - // Try to parse as offset string first (e.g., "+05:00", "-08:00") - if let Some(offset) = parse_timezone_offset(tz) { - let local_dt = utc_dt.to_offset(offset); - format!("{} {}", local_dt, tz) - } else { - // For IANA timezones (e.g., "America/New_York"), we can't do full conversion - // without a timezone database. Just append the timezone name. - format!("{} {}", utc_dt, tz) - } -} - -#[cfg(all(feature = "datetime", feature = "datetime_ops"))] -fn parse_timezone_offset(tz: &str) -> Option { - use crate::structs::variants::datetime::tz::lookup_timezone; - use time::UtcOffset; - // First try timezone database lookup (handles IANA IDs, abbreviations, and direct offsets) - let tz_offset = lookup_timezone(tz)?; - - // Now parse the resolved offset string - let tz = tz_offset.trim(); - - // Handle UTC specially - if tz.eq_ignore_ascii_case("UTC") || tz.eq_ignore_ascii_case("Z") { - return Some(UtcOffset::UTC); - } - - // Parse offset strings like "+05:00", "-08:00", "+0530" - if !tz.starts_with('+') && !tz.starts_with('-') { - return None; - } - - let (sign, rest) = tz.split_at(1); - let sign = if sign == "+" { 1 } else { -1 }; - - // Try parsing HH:MM format - if let Some((hours_str, mins_str)) = rest.split_once(':') { - let hours: i8 = hours_str.parse().ok()?; - let mins: i8 = mins_str.parse().ok()?; - let seconds = sign * (hours as i32 * 3600 + mins as i32 * 60); - return UtcOffset::from_whole_seconds(seconds).ok(); - } - - // Try parsing HHMM format - if rest.len() == 4 { - let hours: i8 = rest[0..2].parse().ok()?; - let mins: i8 = rest[2..4].parse().ok()?; - let seconds = sign * (hours as i32 * 3600 + mins as i32 * 60); - return UtcOffset::from_whole_seconds(seconds).ok(); - } - - None + let v = arr.data[idx]; + let suffix = match arr.time_unit() { + TimeUnit::Seconds => "s", + TimeUnit::Milliseconds => "ms", + TimeUnit::Microseconds => "µs", + TimeUnit::Nanoseconds => "ns", + TimeUnit::Days => "d", + }; + format!("{v}{suffix}") } #[cfg(test)] @@ -509,4 +468,173 @@ mod tests { assert!(display.contains("678.90"), "display should contain 678.90, got: {}", display); assert!(display.contains("1.00"), "display should contain 1.00, got: {}", display); } + + #[cfg(feature = "datetime_ops")] + fn timestamp_array(values: &[Option], dtype: crate::Dt) -> crate::DatetimeArray { + let data: Vec = values.iter().map(|v| v.unwrap_or(0)).collect(); + let mut arr = crate::DatetimeArray::::from_slice(&data, dtype); + if values.iter().any(|v| v.is_none()) { + arr.null_mask = Some(crate::Bitmask::from_bools( + &values.iter().map(|v| v.is_some()).collect::>(), + )); + } + arr + } + + // Asserts the text through `Array::value_to_string`, `DatetimeArray` Display and + // `FieldArray` Display for each value of a 64-bit datetime array. + #[cfg(feature = "datetime_ops")] + fn assert_datetime_text(arr: crate::DatetimeArray, expected: &[&str]) { + let list = format!("[{}]", expected.join(", ")); + assert_eq!(arr.to_string().lines().last(), Some(list.as_str())); + + let array = Array::from_datetime_i64(arr); + for (i, text) in expected.iter().enumerate() { + assert_eq!(array.value_to_string(i), *text); + } + + let field_array = crate::FieldArray::from_arr("ts", array); + let display = field_array.to_string(); + assert_eq!(display.lines().last(), Some(list.as_str())); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_date32_prints_iso_date() { + use crate::{DatetimeArray, Dt}; + let mut arr = DatetimeArray::::from_slice(&[20461, 0, -1], Dt::Date32); + arr.null_mask = Some(crate::Bitmask::from_bools(&[true, true, false])); + assert_eq!(arr.to_string().lines().last(), Some("[2026-01-08, 1970-01-01, null]")); + + let array = Array::from_datetime_i32(arr); + assert_eq!(array.value_to_string(0), "2026-01-08"); + assert_eq!(array.value_to_string(1), "1970-01-01"); + assert_eq!(array.value_to_string(2), "null"); + + let display = crate::FieldArray::from_arr("d", array).to_string(); + assert_eq!(display.lines().last(), Some("[2026-01-08, 1970-01-01, null]")); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_date64_prints_iso_date() { + use crate::Dt; + let arr = timestamp_array(&[Some(1_767_830_400_000), None], Dt::Date64); + assert_datetime_text(arr, &["2026-01-08", "null"]); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_timestamp_seconds_prints_iso_datetime() { + use crate::{Dt, TimeUnit}; + let arr = timestamp_array( + &[Some(1_767_259_800), None, Some(0)], + Dt::Timestamp(TimeUnit::Seconds, None), + ); + assert_datetime_text(arr, &["2026-01-01 09:30:00", "null", "1970-01-01 00:00:00"]); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_timestamp_milliseconds_prints_three_fraction_digits() { + use crate::{Dt, TimeUnit}; + let arr = timestamp_array( + &[Some(1_767_259_800_123), Some(1_767_259_800_000), None], + Dt::Timestamp(TimeUnit::Milliseconds, None), + ); + assert_datetime_text( + arr, + &["2026-01-01 09:30:00.123", "2026-01-01 09:30:00.000", "null"], + ); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_timestamp_microseconds_prints_six_fraction_digits() { + use crate::{Dt, TimeUnit}; + let arr = timestamp_array( + &[Some(1_767_259_800_500_000), Some(1_767_259_800_000_000), Some(1_767_259_800_000_250)], + Dt::Timestamp(TimeUnit::Microseconds, None), + ); + assert_datetime_text( + arr, + &["2026-01-01 09:30:00.500000", "2026-01-01 09:30:00.000000", "2026-01-01 09:30:00.000250"], + ); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_timestamp_nanoseconds_prints_nine_fraction_digits() { + use crate::{Dt, TimeUnit}; + let arr = timestamp_array( + &[Some(1_767_259_800_000_000_001), Some(1_767_259_800_000_000_000), None], + Dt::Timestamp(TimeUnit::Nanoseconds, None), + ); + assert_datetime_text( + arr, + &["2026-01-01 09:30:00.000000001", "2026-01-01 09:30:00.000000000", "null"], + ); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_timestamp_with_time_zone_prints_utc_value_with_utc_offset() { + use crate::{Dt, TimeUnit}; + for tz in ["+05:00", "AEST", "Asia/Tokyo", "Australia/Sydney", "UTC", "Mars/Olympus_Mons"] { + let arr = timestamp_array( + &[Some(1_767_259_800), None], + Dt::Timestamp(TimeUnit::Seconds, Some(tz.into())), + ); + assert_datetime_text(arr, &["2026-01-01 09:30:00+00:00", "null"]); + } + let arr = timestamp_array( + &[Some(1_767_259_800_250_000)], + Dt::Timestamp(TimeUnit::Microseconds, Some("Australia/Sydney".into())), + ); + assert_datetime_text(arr, &["2026-01-01 09:30:00.250000+00:00"]); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_time_of_day_prints_hours_minutes_seconds() { + use crate::{DatetimeArray, Dt, TimeUnit}; + let mut arr = DatetimeArray::::from_slice(&[34_200, 0, 86_399, 0], Dt::Time32(TimeUnit::Seconds)); + arr.null_mask = Some(crate::Bitmask::from_bools(&[true, true, true, false])); + assert_eq!(arr.to_string().lines().last(), Some("[09:30:00, 00:00:00, 23:59:59, null]")); + + let arr = timestamp_array( + &[Some(34_200_250_000), Some(0), None], + Dt::Time64(TimeUnit::Microseconds), + ); + assert_datetime_text(arr, &["09:30:00.250000", "00:00:00.000000", "null"]); + + let arr = timestamp_array(&[Some(34_200_000_000_001)], Dt::Time64(TimeUnit::Nanoseconds)); + assert_datetime_text(arr, &["09:30:00.000000001"]); + } + + #[cfg(feature = "datetime_ops")] + #[test] + fn test_durations_print_count_with_unit_suffix() { + use crate::{DatetimeArray, Dt, TimeUnit}; + let arr = timestamp_array(&[Some(90), Some(-5), None], Dt::Duration64(TimeUnit::Seconds)); + assert_datetime_text(arr, &["90s", "-5s", "null"]); + + let arr = DatetimeArray::::from_slice(&[1_500], Dt::Duration32(TimeUnit::Milliseconds)); + assert_eq!(arr.to_string().lines().last(), Some("[1500ms]")); + } + + #[cfg(all(feature = "datetime", not(feature = "datetime_ops")))] + #[test] + fn test_datetime_prints_raw_value_without_datetime_ops() { + use crate::{DatetimeArray, Dt, TimeUnit}; + let date = Array::from_datetime_i32(DatetimeArray::from_slice(&[20461], Dt::Date32)); + assert_eq!(date.value_to_string(0), "20461d"); + let ts = DatetimeArray::::from_slice( + &[1_767_259_800_000_000], + Dt::Timestamp(TimeUnit::Microseconds, None), + ); + assert_eq!(ts.to_string().lines().last(), Some("[1767259800000000µs]")); + let ts = Array::from_datetime_i64(ts); + assert_eq!(ts.value_to_string(0), "1767259800000000µs"); + } } diff --git a/src/utils.rs b/src/utils.rs index 41a9831..b910c4a 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -66,12 +66,29 @@ pub fn parse_datetime_str(s: &str) -> Option { #[cfg(feature = "datetime_ops")] { + use std::sync::LazyLock; use time::{ Date, OffsetDateTime, PrimitiveDateTime, Time, - format_description::well_known::{Iso8601, Rfc3339}, - macros::format_description, + format_description::{ + self, BorrowedFormatItem, + well_known::{Iso8601, Rfc3339}, + }, }; + // The format descriptions are parsed on first use. + static DATE_TIME_FORMAT: LazyLock>> = LazyLock::new(|| { + format_description::parse_borrowed::<1>("[year]-[month]-[day] [hour]:[minute]:[second]") + .expect("the date-time format description is valid") + }); + static DATE_FORMAT: LazyLock>> = LazyLock::new(|| { + format_description::parse_borrowed::<1>("[year]-[month]-[day]") + .expect("the date format description is valid") + }); + static TIME_FORMAT: LazyLock>> = LazyLock::new(|| { + format_description::parse_borrowed::<1>("[hour]:[minute]:[second]") + .expect("the time format description is valid") + }); + // Try to parse as RFC3339/ISO8601 string (with timezone) if let Ok(dt) = OffsetDateTime::parse(s, &Rfc3339) { return Some(dt.unix_timestamp() * 1_000 + (dt.nanosecond() / 1_000_000) as i64); @@ -83,8 +100,7 @@ pub fn parse_datetime_str(s: &str) -> Option { } // Try parsing as full date-time (no timezone) "%Y-%m-%d %H:%M:%S" - let format = format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"); - if let Ok(dt) = PrimitiveDateTime::parse(s, format) { + if let Ok(dt) = PrimitiveDateTime::parse(s, DATE_TIME_FORMAT.as_slice()) { let dt_utc = dt.assume_utc(); return Some( dt_utc.unix_timestamp() * 1_000 + (dt_utc.nanosecond() / 1_000_000) as i64, @@ -92,8 +108,7 @@ pub fn parse_datetime_str(s: &str) -> Option { } // Try parsing as date only "%Y-%m-%d" - let date_format = format_description!("[year]-[month]-[day]"); - if let Ok(date) = Date::parse(s, date_format) { + if let Ok(date) = Date::parse(s, DATE_FORMAT.as_slice()) { if let Ok(dt) = date.with_hms(0, 0, 0) { let dt_utc = dt.assume_utc(); return Some(dt_utc.unix_timestamp() * 1_000); @@ -101,8 +116,7 @@ pub fn parse_datetime_str(s: &str) -> Option { } // Try parsing as time only "%H:%M:%S" (use today's date) - let time_format = format_description!("[hour]:[minute]:[second]"); - if let Ok(time) = Time::parse(s, time_format) { + if let Ok(time) = Time::parse(s, TIME_FORMAT.as_slice()) { let today = OffsetDateTime::now_utc().date(); let dt_primitive = today.with_time(time); let dt_utc = dt_primitive.assume_utc(); @@ -481,3 +495,42 @@ pub fn create_aligned_chunks_from_array( Ok(SuperArray::from_chunks(chunks?)) } + +#[cfg(all(test, feature = "datetime_ops"))] +mod datetime_text_tests { + use super::parse_datetime_str; + + // Milliseconds since the epoch of 2026-01-01 09:30:00 UTC and of that day at midnight. + const INSTANT_MS: i64 = 1_767_259_800_000; + const MIDNIGHT_MS: i64 = 1_767_225_600_000; + + #[test] + fn test_rfc3339_and_iso8601_text_parses() { + assert_eq!(parse_datetime_str("2026-01-01T09:30:00Z"), Some(INSTANT_MS)); + assert_eq!(parse_datetime_str("2026-01-01T19:30:00+10:00"), Some(INSTANT_MS)); + assert_eq!(parse_datetime_str("2026-01-01T09:30:00.123Z"), Some(INSTANT_MS + 123)); + } + + #[test] + fn test_date_time_text_without_time_zone_parses_as_utc() { + assert_eq!(parse_datetime_str("2026-01-01 09:30:00"), Some(INSTANT_MS)); + } + + #[test] + fn test_date_text_parses_as_midnight_utc() { + assert_eq!(parse_datetime_str("2026-01-01"), Some(MIDNIGHT_MS)); + } + + #[test] + fn test_time_text_parses_as_that_time_today() { + let parsed = parse_datetime_str("09:30:00").expect("the time text parses"); + assert_eq!(parsed.rem_euclid(86_400_000), 34_200_000); + } + + #[test] + fn test_integer_text_parses_as_milliseconds() { + assert_eq!(parse_datetime_str("1767259800000"), Some(INSTANT_MS)); + assert_eq!(parse_datetime_str(""), None); + assert_eq!(parse_datetime_str("not a date"), None); + } +}