Andrea Ciufo
Andrea Ciufo

Reputation: 369

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

I have the following list of integers containing Years and I want to convert to 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)

Output:

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

Why I can't do something more direct like:

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

Why I have to convert first to a string datatype?

There is any better option available?

Upvotes: 2

Views: 316

Answers (1)

jezrael
jezrael

Reputation: 862671

I think reason is unit parameter in to_datetime working different, working with unix times:

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.

But if values are years in integers it is only different format of datetime, so for me this is more logic using here.

Upvotes: 1

Related Questions