|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import typing |
| 16 | + |
| 17 | +from bigframes_vendored.pandas.core.tools import ( |
| 18 | + timedeltas as vendored_pandas_timedeltas, |
| 19 | +) |
| 20 | +import pandas as pd |
| 21 | + |
| 22 | +from bigframes import operations as ops |
| 23 | +from bigframes import series |
| 24 | + |
| 25 | + |
| 26 | +def to_timedelta( |
| 27 | + arg: typing.Union[series.Series, str, int, float], |
| 28 | + unit: typing.Optional[vendored_pandas_timedeltas.UnitChoices] = None, |
| 29 | +) -> typing.Union[series.Series, pd.Timedelta]: |
| 30 | + if not isinstance(arg, series.Series): |
| 31 | + return pd.to_timedelta(arg, unit) |
| 32 | + |
| 33 | + canonical_unit = "us" if unit is None else _canonicalize_unit(unit) |
| 34 | + return arg._apply_unary_op(ops.ToTimedeltaOp(canonical_unit)) |
| 35 | + |
| 36 | + |
| 37 | +to_timedelta.__doc__ = vendored_pandas_timedeltas.to_timedelta.__doc__ |
| 38 | + |
| 39 | + |
| 40 | +def _canonicalize_unit( |
| 41 | + unit: vendored_pandas_timedeltas.UnitChoices, |
| 42 | +) -> typing.Literal["us", "ms", "s", "m", "h", "d", "W"]: |
| 43 | + if unit in {"w", "W"}: |
| 44 | + return "W" |
| 45 | + |
| 46 | + if unit in {"D", "d", "days", "day"}: |
| 47 | + return "d" |
| 48 | + |
| 49 | + if unit in {"hours", "hour", "hr", "h"}: |
| 50 | + return "h" |
| 51 | + |
| 52 | + if unit in {"m", "minute", "min", "minutes"}: |
| 53 | + return "m" |
| 54 | + |
| 55 | + if unit in {"s", "seconds", "sec", "second"}: |
| 56 | + return "s" |
| 57 | + |
| 58 | + if unit in {"ms", "milliseconds", "millisecond", "milli", "millis"}: |
| 59 | + return "ms" |
| 60 | + |
| 61 | + if unit in {"us", "microseconds", "microsecond", "µs", "micro", "micros"}: |
| 62 | + return "us" |
| 63 | + |
| 64 | + raise TypeError(f"Unrecognized unit: {unit}") |
0 commit comments