Erin Erin - 3 years ago 190
Python Question

Failing to convert Pandas dataframe timestamp

I'm pretty new to working with Pandas and am trying to figure out why this timestamp won't convert. As an example, one individual timestamp is the string

'2010-10-06 16:38:02'
. The code looks like this:

newdata = pd.DataFrame.from_records(data, columns = ["col1", "col2", "col3", "timestamp"], index = "timestamp")
newdata.index = newdata.index.tz_localize('UTC').tz_convert('US/Eastern')


And gets this error:

AttributeError: 'Index' object has no attribute 'tz_localize'


Someone commented here that tz_localize is not a method available to Index types, so I tried converting it as a column instead but that gave the error

TypeError: index is not a valid DatetimeIndex or PeriodIndex


And then I found this site, which says tz_localize only acts on the index, anyway.

If anyone could help me out it would be much appreciated! I'm using Pandas 0.15.2. I believe this code may have worked for someone else with an earlier version, but I can't switch.

EDIT:

Ok after messing around a little I found that this doesn't throw any errors and seemed to do what I want in the short-term:
newdata.index=pd.DatetimeIndex(newdata.index).tz_localize('UTC').tz_convert('US/‌​Eastern')

Answer Source

I've been asked to add a formal answer instead of just editing my question, so here it is. Note it builds off the answer above, but that that one didn't quite work for me.

newdata.index=pd.DatetimeIndex(newdata.index).tz_localize('UTC').tz_convert('US/‌​Eastern')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download