Home > Mobile >  Convert Integer or Float to Year?
Convert Integer or Float to Year?

Time:11-03

I am trying to convert a column with type Integer to Year. Here is my situation:

Original Column: June 13, 1980 (United States)

I split and slice it into

Year Column: 1980

Here, I tried to use:

df['Year'] = pd.to_datetime(df['Year']) 

It changed the column to have the year is different from the Original column. For example,

Original     Year
1980         1970
2000         1970
2016         1970

I am looking forward to your help. Thank you in advance.

Best Regards, Tu Le

CodePudding user response:

If need datetimes from year, it means also added month=1 and day=1 add format parameter, here %Y for YYYY:

df['Year'] = pd.to_datetime(df['Year'], format='%Y') 
print (df)
   Original       Year
0      1980 1970-01-01
1      2000 1970-01-01
2      2016 1970-01-01

CodePudding user response:

df['Year'] = df['Original'].astype(str).astype('datetime64')
print(df)

Prints:

  Original       Year
0     1980 1980-01-01
1     2000 2000-01-01
2     2016 2016-01-01
  • Related