Reputation: 103
I have a pandas series/dataframe that has some built in time index which is of pandas.core.indexes.base.Index
type. It goes like this:
Index(['2015-07-13', '2015-07-14',...],
dtype='object', length=1238)
I want to convert this time index, a list-like thing to a list of strictly datetime.date
type thing such that Matplotlib can plot the converted list on the x axis.
To be specific, I want it to be converted and have a format looking like this list:
[datetime.date(2015, 7, 13),datetime.date(2015, 7, 14),datetime.date(2015, 7, 15),
datetime.date(2015, 7, 16),...]
Btw, the way I the list above is through this simple block of code:
dates = [datetime.date(2015, 7, 13)]
num=len(ts_test.index)
for _ in range(num-1):
dates.append(dates[-1] + datetime.timedelta(days=1))
The problem is that the time index I try to plot on the x-axis skips weekends and such, so the list "dates" here has all the unwanted weekends and holidays.
so to put it simply, how to convert '2015-07-13'
, a string to datetime.date(2015, 7, 13)
?
Thank you very much!
Upvotes: 0
Views: 432
Reputation: 76
If you want to convert your index column, of type string, to an index column of type timestamp, a straightforward solution could be:
dates_test.index = pd.to_datetime(dates_test.index)
To extract a list later on:
timeList = dates_test.index.to_list()
Upvotes: 1
Reputation: 103
I ran into a solution and it works nicely!
dates_test=[]
for i in ts_test.index:
date_str=i
format_str='%Y-%m-%d'
datetime_obj = datetime.datetime.strptime(date_str, format_str)
dates_test.append(datetime_obj.date())
So now you have managed to convert a list of str to a list of datetime type of objects which Matplotlib can fully handle and plot nicely along the X-axis!
Upvotes: 0