-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
  • 179,855
  • 19
  • 132
  • 245
  • Is there any reason you can't use the year as a numeric value instead? – Code-Apprentice May 15 '19 at 21:59
  • What is `Date`? We can't really do too much to help if we don't even know what you are running calculations with. I would recommend editing your post into a MCVE as described [here](https://stackoverflow.com/help/reprex) – Reedinationer May 15 '19 at 22:02
  • This might help [Convert year string into datetime object](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – Vasu Deo.S May 15 '19 at 22:17

2 Answers2

1

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,661
  • 1
  • 12
  • 33
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,809
  • 1
  • 14
  • 20