Localize timestamp in pandas

There are a few questions about how to localize the timestamp in pandas, but each of them requires the column to be localized as an index. I do not want this, I want to localize a column that is not an index, for example:

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

this will return me an error:

TypeError: index is not a valid DatetimeIndex or PeriodIndex

My goal is to convert the timestamp to my local time (CEST) using pandas ( datetimedoes this automatically).

+4
source share
1 answer

You need to use .dtwhen working on Seriesnot 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 method tz_localizeis available only for objects DatetimeIndex, therefore, an error, but accessible through dtaccessor

+7

Source: https://habr.com/ru/post/1629149/


All Articles