Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localize timestamp in pandas

There are some questions about how to localiza a timestamp in pandas, but all of them require the column to be localized to be the index. I don't want that, I want to localize a column, which in not the index, for example:

df = pd.DataFrame({'start': pd.to_datetime([1439687730.439, 1439687731.439], unit='s')})
df['start'].tz_localize('utc')

this return me an error:

TypeError: index is not a valid DatetimeIndex or PeriodIndex

My goal is to convert the timestamp in my localtime (CEST) using pandas (datetime does it automatically).

like image 725
Ruggero Turra Avatar asked Feb 17 '16 10:02

Ruggero Turra


1 Answers

You need to use .dt accessor as you're operating on a Series not a DatetimeIndex:

In [191]:
df = pd.DataFrame({'start': pd.to_datetime([1439687730.439, 1439687731.439], unit='s')})
df['start'].dt.tz_localize('utc')

Out[191]:
0   2015-08-16 01:15:30.439000+00:00
1   2015-08-16 01:15:31.439000+00:00
Name: start, dtype: datetime64[ns, UTC]

the tz_localize method is only available on datetimeIndex objects hence the error but it's available through the dt accessor

like image 160
EdChum Avatar answered Oct 09 '22 06:10

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!