Skip to content

Commit b234cf6

Browse files
committed
ENH: Overload to_datetime when errors is coerce
Have to_datetime possibly returning NaTType when errors are coerce and scalar input
1 parent e43cf06 commit b234cf6

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

pandas-stubs/core/tools/datetimes.pyi

+17-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from datetime import datetime as datetime
22
from typing import (
33
List,
4+
Literal,
45
Optional,
56
Tuple,
67
TypedDict,
@@ -18,6 +19,7 @@ from pandas.core.series import (
1819
TimestampSeries,
1920
)
2021

22+
from pandas._libs.tslibs import NaTType
2123
from pandas._typing import (
2224
AnyArrayLike as AnyArrayLike,
2325
ArrayLike as ArrayLike,
@@ -61,7 +63,7 @@ def should_cache(
6163
@overload
6264
def to_datetime(
6365
arg: DatetimeScalar,
64-
errors: DateTimeErrorChoices = ...,
66+
errors: Literal["ignore", "raise"] = ...,
6567
dayfirst: bool = ...,
6668
yearfirst: bool = ...,
6769
utc: bool | None = ...,
@@ -73,6 +75,20 @@ def to_datetime(
7375
cache: bool = ...,
7476
) -> Timestamp: ...
7577
@overload
78+
def to_datetime(
79+
arg: DatetimeScalar,
80+
errors: Literal["coerce"],
81+
dayfirst: bool = ...,
82+
yearfirst: bool = ...,
83+
utc: bool | None = ...,
84+
format: str | None = ...,
85+
exact: bool = ...,
86+
unit: str | None = ...,
87+
infer_datetime_format: bool = ...,
88+
origin=...,
89+
cache: bool = ...,
90+
) -> Timestamp | NaTType: ...
91+
@overload
7692
def to_datetime(
7793
arg: Series | DictConvertible,
7894
errors: DateTimeErrorChoices = ...,

tests/test_timefuncs.py

+11
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,16 @@
44
from typing import (
55
TYPE_CHECKING,
66
Optional,
7+
Union,
78
)
89

910
import numpy as np
1011
from numpy import typing as npt
1112
import pandas as pd
1213
from typing_extensions import assert_type
1314

15+
from pandas._libs import NaTType
16+
1417
if TYPE_CHECKING:
1518
from pandas.core.series import (
1619
TimedeltaSeries,
@@ -209,3 +212,11 @@ def test_comparisons_datetimeindex() -> None:
209212
assert_type((dti <= ts), np_ndarray_bool)
210213
assert_type((dti == ts), np_ndarray_bool)
211214
assert_type((dti != ts), np_ndarray_bool)
215+
216+
217+
def test_to_datetime_nat() -> None:
218+
assert_type(pd.to_datetime("2021-03-01", errors="ignore"), "pd.Timestamp")
219+
assert_type(pd.to_datetime("2021-03-01", errors="raise"), "pd.Timestamp")
220+
assert_type(
221+
pd.to_datetime("2021-03-01", errors="coerce"), "Union[pd.Timestamp, NaTType]"
222+
)

0 commit comments

Comments
 (0)