将由 int 数据类型表示的年份列表转换为 DatetimeIndex 的更好方法

Better way to convert a list of Years expressed by a int datatype to DatetimeIndex

我有以下包含年份的整数列表,我想转换为 DatetimeIndex。

date_1=[2000,2001,2002,2003]
#converting to string
date_1_str=[str(i) for i in date_1]
#converting to Datetime
test=pd.to_datetime(date_1_str,format="%Y")
print(test)

输出:

DatetimeIndex(['2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01'], dtype='datetime64[ns]', freq=None)

为什么我不能做更直接的事情,例如:

pd.to_datetime(date_1, unit="Y") 

为什么我必须先转换为字符串数据类型?

有更好的选择吗?

我认为原因是 to_datetime 中的 unit 参数工作不同,使用 unix 时间:

unit , default ‘ns’

The unit of the arg (D,s,ms,us,ns) denote the unit, which is an integer or float number. This will be based off the origin. Example, with unit=’ms’ and origin=’unix’ (the default), this would calculate the number of milliseconds to the unix epoch start.

但是如果值是整数年,它只是 format 日期时间不同,所以对我来说,在这里使用更符合逻辑。