0

I feel annoying to change datetime format.

y_hat.head()

    0       year
0   649.003 1960-12-31
1   649.003 1961-12-31
2   649.003 1962-12-31
3   649.003 1963-12-31
4   649.003 1964-12-31

I have one column called['year'], I want to change it from '1960-12-31' to '1960'. I have tried many methods, such as Change datetime format from one to another programmatically Can someone provide a method for me and others?

Michael
  • 529
  • 1
  • 8
  • 22

1 Answers1

2

You can convert column to_datetime and extract year:

df['year'] = pd.to_datetime(df['year']).dt.year

Or split and extract first value of lists, then convert to integers:

df['year'] = df['year'].str.split('-').str[0].astype(int)

print (df)
         0  year
0  649.003  1960
1  649.003  1961
2  649.003  1962
3  649.003  1963
4  649.003  1964
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252