pola-rs/polars · error

can only convert date/datetime to NaiveDateTime

Error message

can only convert date/datetime to NaiveDateTime

What it means

AnyValue<'_> has a TryFrom/From conversion into chrono NaiveDateTime that only supports the Date and Datetime variants. If the AnyValue holds any other physical representation (int, string, null, etc.), the impl panics with this message. It is a guard against calling a date-only conversion on a non-date value.

Solutions

  1. Cast the Series/ChunkedArray to Date or Datetime before extracting values (series.cast(&DataType::Datetime(time_unit, tz))).
  2. Match on the AnyValue variant yourself and only convert Date/Datetime variants to NaiveDateTime.
  3. For string inputs, use str.to_date()/str.to_datetime() expression instead of relying on AnyValue conversion.
  4. If the value is Int, convert via timestamp semantics explicitly (e.g. timestamp_ms_to_datetime on the i64).

Example fix

// before
let dt: NaiveDateTime = (&any_value).into(); // panics if not date/datetime
// after
let dt = match any_value {
    AnyValue::Date(_) | AnyValue::Datetime(..) => NaiveDateTime::from(&any_value),
    _ => polars::prelude::Series::new("".into(), [any_value])
        .cast(&DataType::Datetime(TimeUnit::Microseconds, None))?
        .datetime()?.get(0).unwrap(),
};
Defensive patterns

Strategy: type-guard

Validate before calling

fn is_temporal(av: &AnyValue) -> bool {
    matches!(av, AnyValue::Date(_) | AnyValue::Datetime(..))
}

Type guard

if !matches!(av, AnyValue::Date(_) | AnyValue::Datetime(..)) { return Err(...); }

Try / catch

Polars panics are not catchable as Result; ensure variant before conversion:
let dt = if is_temporal(&av) { NaiveDateTime::from(&av) } else { cast_then_convert(&av)? };

Prevention

When it happens

Trigger: Calling .into() / NaiveDateTime::from(&AnyValue) on an AnyValue that is not AnyValue::Date or AnyValue::Datetime, e.g. converting a literal or scalar whose logical dtype is Int64, String, or Null.

Common situations: Formatting a date column's physical values via get() without first cast()ing to Date/Datetime; using a String '2024-01-01' literal directly as a temporal value; downstream code in lazy expressions assuming a value is temporal when the column dtype is not.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/6f3f05bcd1a382d5. Report an issue: GitHub.

Appendix: source

Thrown at crates/polars-core/src/chunked_array/temporal/conversion.rs:22

use crate::prelude::*;

pub(crate) const NS_IN_DAY: i64 = 86_400_000_000_000;
pub(crate) const US_IN_DAY: i64 = 86_400_000_000;
pub(crate) const MS_IN_DAY: i64 = 86_400_000;
pub(crate) const SECONDS_IN_DAY: i64 = 86_400;

impl From<&AnyValue<'_>> for NaiveDateTime {
    fn from(v: &AnyValue) -> Self {
        match v {
            #[cfg(feature = "dtype-date")]
            AnyValue::Date(v) => date32_to_datetime(*v),
            #[cfg(feature = "dtype-datetime")]
            AnyValue::Datetime(v, tu, _) => match tu {
                TimeUnit::Nanoseconds => timestamp_ns_to_datetime(*v),
                TimeUnit::Microseconds => timestamp_us_to_datetime(*v),
                TimeUnit::Milliseconds => timestamp_ms_to_datetime(*v),
            },
            _ => panic!("can only convert date/datetime to NaiveDateTime"),
        }
    }
}

impl From<&AnyValue<'_>> for NaiveTime {
    fn from(v: &AnyValue) -> Self {
        match v {
            #[cfg(feature = "dtype-time")]
            AnyValue::Time(v) => time64ns_to_time(*v),
            _ => panic!("can only convert date/datetime to NaiveTime"),
        }
    }
}

// Used by lazy for literal conversion
pub fn datetime_to_timestamp_ns(v: NaiveDateTime) -> i64 {
    let us = v.and_utc().timestamp() * 1_000_000_000; //nanos
    us + v.and_utc().timestamp_subsec_nanos() as i64

View on GitHub (pinned to fe841f959e)