Skip to content

Commit bbb89ca

Browse files
TYP: some type annotations in core\tools\datetimes.py (#34630)
1 parent c45e92c commit bbb89ca

File tree

5 files changed

+123
-40
lines changed

5 files changed

+123
-40
lines changed

pandas/_typing.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from datetime import datetime, timedelta
1+
from datetime import datetime, timedelta, tzinfo
22
from pathlib import Path
33
from typing import (
44
IO,
@@ -52,6 +52,7 @@
5252
TimedeltaConvertibleTypes = Union[
5353
"Timedelta", timedelta, np.timedelta64, int, np.int64, float, str
5454
]
55+
Timezone = Union[str, tzinfo]
5556

5657
# other
5758

pandas/core/indexes/datetimes.py

+22-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from pandas._libs.tslibs import Resolution, fields, parsing, timezones, to_offset
1010
from pandas._libs.tslibs.offsets import prefix_mapping
1111
from pandas._typing import DtypeObj, Label
12-
from pandas.util._decorators import cache_readonly
12+
from pandas.util._decorators import cache_readonly, doc
1313

1414
from pandas.core.dtypes.common import (
1515
DT64NS_DTYPE,
@@ -63,9 +63,13 @@ def _new_DatetimeIndex(cls, d):
6363

6464

6565
@inherit_names(
66-
["to_period", "to_perioddelta", "to_julian_date", "strftime", "isocalendar"]
66+
["to_perioddelta", "to_julian_date", "strftime", "isocalendar"]
6767
+ DatetimeArray._field_ops
68-
+ DatetimeArray._datetimelike_methods,
68+
+ [
69+
method
70+
for method in DatetimeArray._datetimelike_methods
71+
if method not in ("tz_localize",)
72+
],
6973
DatetimeArray,
7074
wrap=True,
7175
)
@@ -217,6 +221,21 @@ class DatetimeIndex(DatetimeTimedeltaMixin):
217221
_data: DatetimeArray
218222
tz: Optional[tzinfo]
219223

224+
# --------------------------------------------------------------------
225+
# methods that dispatch to array and wrap result in DatetimeIndex
226+
227+
@doc(DatetimeArray.tz_localize)
228+
def tz_localize(
229+
self, tz, ambiguous="raise", nonexistent="raise"
230+
) -> "DatetimeIndex":
231+
arr = self._data.tz_localize(tz, ambiguous, nonexistent)
232+
return type(self)._simple_new(arr, name=self.name)
233+
234+
@doc(DatetimeArray.to_period)
235+
def to_period(self, freq=None) -> "DatetimeIndex":
236+
arr = self._data.to_period(freq)
237+
return type(self)._simple_new(arr, name=self.name)
238+
220239
# --------------------------------------------------------------------
221240
# Constructors
222241

pandas/core/series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4846,7 +4846,7 @@ def to_period(self, freq=None, copy=True) -> "Series":
48464846

48474847
if not isinstance(self.index, DatetimeIndex):
48484848
raise TypeError(f"unsupported Type {type(self.index).__name__}")
4849-
new_index = self.index.to_period(freq=freq) # type: ignore
4849+
new_index = self.index.to_period(freq=freq)
48504850
return self._constructor(new_values, index=new_index).__finalize__(
48514851
self, method="to_period"
48524852
)

pandas/core/tools/datetimes.py

+94-33
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,16 @@
22
from datetime import datetime
33
from functools import partial
44
from itertools import islice
5-
from typing import TYPE_CHECKING, Optional, TypeVar, Union
5+
from typing import (
6+
TYPE_CHECKING,
7+
Callable,
8+
List,
9+
Optional,
10+
Tuple,
11+
TypeVar,
12+
Union,
13+
overload,
14+
)
615
import warnings
716

817
import numpy as np
@@ -15,7 +24,7 @@
1524
_guess_datetime_format,
1625
)
1726
from pandas._libs.tslibs.strptime import array_strptime
18-
from pandas._typing import ArrayLike
27+
from pandas._typing import ArrayLike, Label, Timezone
1928

2029
from pandas.core.dtypes.common import (
2130
ensure_object,
@@ -45,16 +54,15 @@
4554

4655
if TYPE_CHECKING:
4756
from pandas import Series # noqa:F401
57+
from pandas._libs.tslibs.nattype import NaTType # noqa:F401
4858

4959
# ---------------------------------------------------------------------
5060
# types used in annotations
5161

52-
ArrayConvertible = Union[list, tuple, ArrayLike, "Series"]
62+
ArrayConvertible = Union[List, Tuple, ArrayLike, "Series"]
5363
Scalar = Union[int, float, str]
5464
DatetimeScalar = TypeVar("DatetimeScalar", Scalar, datetime)
55-
DatetimeScalarOrArrayConvertible = Union[
56-
DatetimeScalar, list, tuple, ArrayLike, "Series"
57-
]
65+
DatetimeScalarOrArrayConvertible = Union[DatetimeScalar, ArrayConvertible]
5866

5967

6068
# ---------------------------------------------------------------------
@@ -123,7 +131,12 @@ def should_cache(
123131
return do_caching
124132

125133

126-
def _maybe_cache(arg, format, cache, convert_listlike):
134+
def _maybe_cache(
135+
arg: ArrayConvertible,
136+
format: Optional[str],
137+
cache: bool,
138+
convert_listlike: Callable,
139+
) -> "Series":
127140
"""
128141
Create a cache of unique dates from an array of dates
129142
@@ -159,7 +172,7 @@ def _maybe_cache(arg, format, cache, convert_listlike):
159172

160173

161174
def _box_as_indexlike(
162-
dt_array: ArrayLike, utc: Optional[bool] = None, name: Optional[str] = None
175+
dt_array: ArrayLike, utc: Optional[bool] = None, name: Label = None
163176
) -> Index:
164177
"""
165178
Properly boxes the ndarray of datetimes to DatetimeIndex
@@ -244,15 +257,15 @@ def _return_parsed_timezone_results(result, timezones, tz, name):
244257

245258
def _convert_listlike_datetimes(
246259
arg,
247-
format,
248-
name=None,
249-
tz=None,
250-
unit=None,
251-
errors=None,
252-
infer_datetime_format=None,
253-
dayfirst=None,
254-
yearfirst=None,
255-
exact=None,
260+
format: Optional[str],
261+
name: Label = None,
262+
tz: Optional[Timezone] = None,
263+
unit: Optional[str] = None,
264+
errors: Optional[str] = None,
265+
infer_datetime_format: Optional[bool] = None,
266+
dayfirst: Optional[bool] = None,
267+
yearfirst: Optional[bool] = None,
268+
exact: Optional[bool] = None,
256269
):
257270
"""
258271
Helper function for to_datetime. Performs the conversions of 1D listlike
@@ -306,9 +319,7 @@ def _convert_listlike_datetimes(
306319
pass
307320
elif tz:
308321
# DatetimeArray, DatetimeIndex
309-
# error: Item "DatetimeIndex" of "Union[DatetimeArray, DatetimeIndex]" has
310-
# no attribute "tz_localize"
311-
return arg.tz_localize(tz) # type: ignore
322+
return arg.tz_localize(tz)
312323

313324
return arg
314325

@@ -539,19 +550,70 @@ def _adjust_to_origin(arg, origin, unit):
539550
return arg
540551

541552

553+
@overload
542554
def to_datetime(
543-
arg,
544-
errors="raise",
545-
dayfirst=False,
546-
yearfirst=False,
547-
utc=None,
548-
format=None,
549-
exact=True,
550-
unit=None,
551-
infer_datetime_format=False,
555+
arg: DatetimeScalar,
556+
errors: str = ...,
557+
dayfirst: bool = ...,
558+
yearfirst: bool = ...,
559+
utc: Optional[bool] = ...,
560+
format: Optional[str] = ...,
561+
exact: bool = ...,
562+
unit: Optional[str] = ...,
563+
infer_datetime_format: bool = ...,
564+
origin=...,
565+
cache: bool = ...,
566+
) -> Union[DatetimeScalar, "NaTType"]:
567+
...
568+
569+
570+
@overload
571+
def to_datetime(
572+
arg: "Series",
573+
errors: str = ...,
574+
dayfirst: bool = ...,
575+
yearfirst: bool = ...,
576+
utc: Optional[bool] = ...,
577+
format: Optional[str] = ...,
578+
exact: bool = ...,
579+
unit: Optional[str] = ...,
580+
infer_datetime_format: bool = ...,
581+
origin=...,
582+
cache: bool = ...,
583+
) -> "Series":
584+
...
585+
586+
587+
@overload
588+
def to_datetime(
589+
arg: Union[List, Tuple],
590+
errors: str = ...,
591+
dayfirst: bool = ...,
592+
yearfirst: bool = ...,
593+
utc: Optional[bool] = ...,
594+
format: Optional[str] = ...,
595+
exact: bool = ...,
596+
unit: Optional[str] = ...,
597+
infer_datetime_format: bool = ...,
598+
origin=...,
599+
cache: bool = ...,
600+
) -> DatetimeIndex:
601+
...
602+
603+
604+
def to_datetime(
605+
arg: DatetimeScalarOrArrayConvertible,
606+
errors: str = "raise",
607+
dayfirst: bool = False,
608+
yearfirst: bool = False,
609+
utc: Optional[bool] = None,
610+
format: Optional[str] = None,
611+
exact: bool = True,
612+
unit: Optional[str] = None,
613+
infer_datetime_format: bool = False,
552614
origin="unix",
553-
cache=True,
554-
):
615+
cache: bool = True,
616+
) -> Union[DatetimeIndex, "Series", DatetimeScalar, "NaTType"]:
555617
"""
556618
Convert argument to datetime.
557619
@@ -746,8 +808,7 @@ def to_datetime(
746808
if not cache_array.empty:
747809
result = _convert_and_box_cache(arg, cache_array, name=arg.name)
748810
else:
749-
convert_listlike = partial(convert_listlike, name=arg.name)
750-
result = convert_listlike(arg, format)
811+
result = convert_listlike(arg, format, name=arg.name)
751812
elif is_list_like(arg):
752813
try:
753814
cache_array = _maybe_cache(arg, format, cache, convert_listlike)

pandas/io/excel/_odfreader.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List
1+
from typing import List, cast
22

33
from pandas._typing import FilePathOrBuffer, Scalar
44
from pandas.compat._optional import import_optional_dependency
@@ -179,7 +179,9 @@ def _get_cell_value(self, cell, convert_float: bool) -> Scalar:
179179
cell_value = cell.attributes.get((OFFICENS, "date-value"))
180180
return pd.to_datetime(cell_value)
181181
elif cell_type == "time":
182-
return pd.to_datetime(str(cell)).time()
182+
result = pd.to_datetime(str(cell))
183+
result = cast(pd.Timestamp, result)
184+
return result.time()
183185
else:
184186
raise ValueError(f"Unrecognized type {cell_type}")
185187

0 commit comments

Comments
 (0)