-1

I have a date column in my dataframe that consists of strings like this...'201512' I would like to convert it into a datetime object of just year to do some time series analysis.

I tried...

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

and something similar to

datetime.strptime(Date, "%Y")
OneCricketeer
  • 151,199
  • 17
  • 111
  • 216

2 Answers2

0

I would look at the module arrow

https://arrow.readthedocs.io/en/latest/

import arrow
date = arrow.now()
#example of text formatting
fdate = date.format('YYYY')

#example of converting text into datetime
date = arrow.get('201905', 'YYYYMM').datetime
eatmeimadanish
  • 3,552
  • 1
  • 12
  • 19
0

I am not sure how datetime interfaces with pandas dataframes (perhaps somebody will comment if there is special usage), but in general the datetime functions would work like this:

import datetime

date_string = "201512"
date_object = datetime.datetime.strptime(date_string, "%Y%m")
print(date_object)

Getting us:

2015-12-01 00:00:00

Now that the hard part of creating a datetime object is done we simply

print(date_object.year)

Which spits out our desired

2015

More info about the parsing operators (the "%Y%m" bit of my code) is described in the documentation

Reedinationer
  • 5,388
  • 1
  • 11
  • 33