Skip to content

BUG: Constructing series with Timedelta object results in datetime series #61365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
3 tasks done
Casper-Guo opened this issue Apr 27, 2025 · 3 comments
Open
3 tasks done
Labels
Bug Constructors Series/DataFrame/Index/pd.array Constructors Timedelta Timedelta data type

Comments

@Casper-Guo
Copy link

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

test = pd.Series([pd.Timedelta("NaT")])
print(test)

Issue Description

test is initialized to a series of datetime64 type. This gotcha is not documented anywhere and the result is counter-intuitive. Opening the issue in case this is unintended.

Expected Behavior

test is initialized to a series of timedelta64 type

Installed Versions

INSTALLED VERSIONS

commit : 0691c5c
python : 3.12.3
python-bits : 64
OS : Linux
OS-release : 5.15.167.4-microsoft-standard-WSL2
Version : #1 SMP Tue Nov 5 00:21:55 UTC 2024
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : C.UTF-8

pandas : 2.2.3
numpy : 2.2.3
pytz : 2025.1
dateutil : 2.9.0.post0
pip : 25.0.1
Cython : None
sphinx : 8.2.3
IPython : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.13.3
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : 3.1.5
lxml.etree : None
matplotlib : 3.10.1
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : 8.3.5
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.15.2
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.1
qtpy : None
pyqt5 : None

@Casper-Guo Casper-Guo added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 27, 2025
@arthurlw
Copy link
Member

Thanks for opening this! Confirmed on main. I agree that the behavior feels a bit unintuitive.

@rhshadrach rhshadrach added Timedelta Timedelta data type Constructors Series/DataFrame/Index/pd.array Constructors and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 29, 2025
@arthurlw
Copy link
Member

I did some investigating and found that for datetime-related types (datetime64, timedelta64, etc) with the value pd.NaT, pandas stores them all as <class 'pandas._libs.tslibs.nattype.NaTType'>. This makes it impossible to differentiate between a Timestamp("NaT") and a Timedelta("NaT") during Series construction.

@chilin0525
Copy link
Contributor

chilin0525 commented May 4, 2025

I also traced the source code and it looks like the dtype_if_all_nat is assigned by dtype_if_all_nat in this case. As @arthurlw mentioned, there's no reliable way to determine whether a NaTType originates from a Timestamp or a Timedelta. 😢

# error: Incompatible return value type (got "Union[ExtensionArray,
# ndarray[Any, Any]]", expected "Union[ndarray[Any, Any], DatetimeArray,
# TimedeltaArray, PeriodArray, IntervalArray]")
return lib.maybe_convert_objects( # type: ignore[return-value]
value,
# Here we do not convert numeric dtypes, as if we wanted that,
# numpy would have done it for us.
convert_numeric=False,
convert_non_numeric=True,
convert_to_nullable_dtype=convert_to_nullable_dtype,
dtype_if_all_nat=np.dtype("M8[s]"),
)

pandas/pandas/_libs/lib.pyx

Lines 2808 to 2831 in 337d40e

elif seen.nat_:
if not seen.object_ and not seen.numeric_ and not seen.bool_:
# all NaT, None, or nan (at least one NaT)
# see GH#49340 for discussion of desired behavior
dtype = dtype_if_all_nat
if cnp.PyArray_DescrCheck(dtype):
# i.e. isinstance(dtype, np.dtype)
if dtype.kind not in "mM":
raise ValueError(dtype)
else:
res = np.empty((<object>objects).shape, dtype=dtype)
res[:] = NPY_NAT
return res
elif dtype is not None:
# i.e. PeriodDtype, DatetimeTZDtype
cls = dtype.construct_array_type()
obj = cls._from_sequence([], dtype=dtype)
taker = -np.ones((<object>objects).shape, dtype=np.intp)
return obj.take(taker, allow_fill=True)
else:
# we don't guess
seen.object_ = True
else:
seen.object_ = True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Constructors Series/DataFrame/Index/pd.array Constructors Timedelta Timedelta data type
Projects
None yet
Development

No branches or pull requests

4 participants