Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas convert column with year integer to datetime

I am having some problem converting column (datatype:int64) into datetime working with Pandas.

Original data:

Year
2015
2014
...
2010

Desired outcome:

Year
2015-01-01
2014-01-01
...
2010-01-01

My current result:

Year
1970-01-01 00:00:00.000002015
1970-01-01 00:00:00.000002014
...
1970-01-01 00:00:00.000002010

I have tried:

data.Year = pd.to_datetime(data.Year)
data.Year = pd.to_datetime(data.Year, format='%Y-%m-%d')

Thanks

like image 804
shawnngtq Avatar asked Oct 10 '17 03:10

shawnngtq


People also ask

How do you convert int to datetime in Python?

Use pandas. to_datetime() to Convert Integer to Date & Time Format. Let's suppose that your integers contain both the date and time. In that case, the format should be specify is '%Y%m%d%H%M%S' .

What is the method in pandas to change values into datetime data type?

pandas. to_datetime() method is used to change String/Object time to date type (datetime64[ns]).


1 Answers

Use format='%Y'

In [225]: pd.to_datetime(df.Year, format='%Y')
Out[225]:
0   2015-01-01
1   2014-01-01
2   2010-01-01
Name: Year, dtype: datetime64[ns]

Details

In [226]: df
Out[226]:
   Year
0  2015
1  2014
2  2010
like image 150
Zero Avatar answered Oct 15 '22 04:10

Zero