{"record":{"id":"6f3f05bcd1a382d5","repo":"pola-rs/polars","slug":"can-only-convert-date-datetime-to-naivedatetime","errorCode":null,"errorMessage":"can only convert date/datetime to NaiveDateTime","messagePattern":"can only convert date/datetime to NaiveDateTime","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-core/src/chunked_array/temporal/conversion.rs","lineNumber":22,"sourceCode":"use crate::prelude::*;\n\npub(crate) const NS_IN_DAY: i64 = 86_400_000_000_000;\npub(crate) const US_IN_DAY: i64 = 86_400_000_000;\npub(crate) const MS_IN_DAY: i64 = 86_400_000;\npub(crate) const SECONDS_IN_DAY: i64 = 86_400;\n\nimpl From<&AnyValue<'_>> for NaiveDateTime {\n    fn from(v: &AnyValue) -> Self {\n        match v {\n            #[cfg(feature = \"dtype-date\")]\n            AnyValue::Date(v) => date32_to_datetime(*v),\n            #[cfg(feature = \"dtype-datetime\")]\n            AnyValue::Datetime(v, tu, _) => match tu {\n                TimeUnit::Nanoseconds => timestamp_ns_to_datetime(*v),\n                TimeUnit::Microseconds => timestamp_us_to_datetime(*v),\n                TimeUnit::Milliseconds => timestamp_ms_to_datetime(*v),\n            },\n            _ => panic!(\"can only convert date/datetime to NaiveDateTime\"),\n        }\n    }\n}\n\nimpl From<&AnyValue<'_>> for NaiveTime {\n    fn from(v: &AnyValue) -> Self {\n        match v {\n            #[cfg(feature = \"dtype-time\")]\n            AnyValue::Time(v) => time64ns_to_time(*v),\n            _ => panic!(\"can only convert date/datetime to NaiveTime\"),\n        }\n    }\n}\n\n// Used by lazy for literal conversion\npub fn datetime_to_timestamp_ns(v: NaiveDateTime) -> i64 {\n    let us = v.and_utc().timestamp() * 1_000_000_000; //nanos\n    us + v.and_utc().timestamp_subsec_nanos() as i64","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-core/src/chunked_array/temporal/conversion.rs#L4-L40","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Cast the Series/ChunkedArray to Date or Datetime before extracting values (series.cast(&DataType::Datetime(time_unit, tz))).","Match on the AnyValue variant yourself and only convert Date/Datetime variants to NaiveDateTime.","For string inputs, use str.to_date()/str.to_datetime() expression instead of relying on AnyValue conversion.","If the value is Int, convert via timestamp semantics explicitly (e.g. timestamp_ms_to_datetime on the i64)."],"exampleFix":"// before\nlet dt: NaiveDateTime = (&any_value).into(); // panics if not date/datetime\n// after\nlet dt = match any_value {\n    AnyValue::Date(_) | AnyValue::Datetime(..) => NaiveDateTime::from(&any_value),\n    _ => polars::prelude::Series::new(\"\".into(), [any_value])\n        .cast(&DataType::Datetime(TimeUnit::Microseconds, None))?\n        .datetime()?.get(0).unwrap(),\n};","handlingStrategy":"type-guard","validationCode":"fn is_temporal(av: &AnyValue) -> bool {\n    matches!(av, AnyValue::Date(_) | AnyValue::Datetime(..))\n}","typeGuard":"if !matches!(av, AnyValue::Date(_) | AnyValue::Datetime(..)) { return Err(...); }","tryCatchPattern":"Polars panics are not catchable as Result; ensure variant before conversion:\nlet dt = if is_temporal(&av) { NaiveDateTime::from(&av) } else { cast_then_convert(&av)? };","preventionTips":["Never call .into()/From for NaiveDateTime on unchecked AnyValues","Cast series to Date/Datetime before extracting elements","Handle string dates with str.to_date/to_datetime expressions"],"tags":["polars","panic","temporal","type-mismatch"],"backgroundTag":"type-mismatch","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}