简体   繁体   中英

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')

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')

您必须先将索引列转换为pandas中的系列类型:

newdata.index.to_series().tz_localize('UTC').tz_convert('US/Eastern')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM