Skip to content

Commit

Permalink
fix[rust]: don't unnecessarily truncate datetimes on string casts (#4625
Browse files Browse the repository at this point in the history
)
  • Loading branch information
alexander-beedie committed Aug 30, 2022
1 parent 1deac61 commit c5083a2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
12 changes: 10 additions & 2 deletions polars/polars-core/src/series/implementations/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,16 @@ impl SeriesTrait for SeriesWrap<DatetimeChunked> {
}

fn cast(&self, data_type: &DataType) -> Result<Series> {
match data_type {
DataType::Utf8 => Ok(self.0.strftime("%F %T").into_series()),
match (data_type, self.0.time_unit()) {
(DataType::Utf8, TimeUnit::Milliseconds) => {
Ok(self.0.strftime("%F %T%.3f").into_series())
}
(DataType::Utf8, TimeUnit::Microseconds) => {
Ok(self.0.strftime("%F %T%.6f").into_series())
}
(DataType::Utf8, TimeUnit::Nanoseconds) => {
Ok(self.0.strftime("%F %T%.9f").into_series())
}
_ => self.0.cast(data_type),
}
}
Expand Down
26 changes: 26 additions & 0 deletions py-polars/tests/test_datelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -1426,3 +1426,29 @@ def test_date_timedelta() -> None:
"date_plus_one": [date(2001, 1, 2), date(2001, 1, 3), date(2001, 1, 4)],
"date_min_one": [date(2000, 12, 31), date(2001, 1, 1), date(2001, 1, 2)],
}


def test_datetime_string_casts() -> None:
df = pl.DataFrame(
{
"x": [1661855445123],
"y": [1661855445123456],
"z": [1661855445123456789],
},
columns=[
("x", pl.Datetime("ms")),
("y", pl.Datetime("us")),
("z", pl.Datetime("ns")),
],
)
assert df.select(
[pl.col("x").dt.strftime("%F %T").alias("w")]
+ [pl.col(d).cast(str) for d in df.columns]
).rows() == [
(
"2022-08-30 10:30:45",
"2022-08-30 10:30:45.123",
"2022-08-30 10:30:45.123456",
"2022-08-30 10:30:45.123456789",
)
]

0 comments on commit c5083a2

Please sign in to comment.