(df: pl.DataFrame)
| 77 | # Timestamp strings from the Rust bindings: "%Y-%m-%d %H:%M:%S" with an optional fractional |
| 78 | # second (6 digits, or 9 below a microsecond). polars infers a format from the first value only, so a column |
| 79 | # mixing whole and fractional seconds must be parsed with this explicit format. |
| 80 | TS_FORMAT = "%Y-%m-%d %H:%M:%S%.f" |
| 81 | |
| 82 | |
| 83 | def _parse_ts(expr: pl.Expr) -> pl.Expr: |
| 84 | """Parse timestamp strings to UTC-naive datetimes, keeping microseconds. |
| 85 | |
| 86 | Strings in `TS_FORMAT` are parsed with it; anything else (dates, ISO `T` forms) falls back |
| 87 | to polars' format inference, as before. |
| 88 | """ |
| 89 | # strict=False turns bad values into nulls, but inference still raises if *none* |
| 90 | # can be parsed. A final known-valid date lets inference finish in that case; |
| 91 | # remove it before returning so empty/all-invalid inputs keep their original size. |
| 92 | utc_dtype = pl.Datetime(time_unit="us", time_zone="UTC") |
| 93 | inferred = ( |
| 94 | expr.append(pl.lit("2000-01-01")).str.strptime(utc_dtype, strict=False).head(expr.len()) |
| 95 | ) |
| 96 | # An explicit zone is required for offset-aware strings in a lazy plan. |
| 97 | # Normalize to UTC before dropping the zone to keep the canonical naive schema. |
| 98 | return pl.coalesce( |
| 99 | expr.str.strptime(utc_dtype, TS_FORMAT, strict=False), |
no test coverage detected