jmbejara / comp-econ-sp18

Main Course Repository for Computational Methods in Economics (Econ 21410, Spring 2018)
16 stars 23 forks source link

Time series (np.datetime64) #44

Closed BejaKi closed 6 years ago

BejaKi commented 6 years ago

Is there a way to convert a date (dtype = object) into dtype datetime64 when the date is given in the format "Jan-04" to mean January 2004?

jmbejara commented 6 years ago

Yeah! Here is an example:

import pandas as pd
dates = ['Jan-04', 'Mar-99', 'Dec-18']
pd.to_datetime(dates, format='%b-%y')

The output is

DatetimeIndex(['2004-01-01', '1999-03-01', '2018-12-01'], dtype='datetime64[ns]', freq=None)

Use the format keyword to supply the format if the function to_datetime can't figure it out on its own. The documentation for to_datatime is here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html

For a reference on the different values to choose for the strftime format, check out this reference here: http://strftime.org/ or here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

BejaKi commented 6 years ago

Thank you!