Python | Панды DatetimeIndex.tz_localize ()
Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.
Pandas DatetimeIndex.tz_localize() function localize tz-naive DatetimeIndex to tz-aware DatetimeIndex. This method takes a time zone (tz) naive DatetimeIndex object and makes this time zone aware. It does not move the time to another time zone. Time zone localization helps to switch from time zone aware to time zone unaware objects.
Syntax: DatetimeIndex.tz_localize(tz, ambiguous=’raise’, errors=’raise’)
Parameters :
tz : Time zone to convert timestamps to tz-aware DatetimeIndex. Passing None will remove the time zone information preserving local time.
ambiguous : str {‘infer’, ‘NaT’, ‘raise’} or bool array, default ‘raise’
errors : {‘raise’, ‘coerce’}, default ‘raise’Return : Index converted to the specified time zone.
Example #1: Use DatetimeIndex.tz_localize() function to make the naive DatetimeIndex object to an object that is time zone aware.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here "Q" represents quarter end frequency didx = pd.DatetimeIndex(start ="2000-01-15 08:00", freq ="Q", periods = 4) # Print the DatetimeIndexprint(didx) |
Выход :
Now we want to convert the naive DatetimeIndex object into a timezone aware object
# make timezone awaredidx.tz_localize(tz ="Europe/Berlin") |
Output :
As we can see in the output, the function has introduced timezone awareness into the didx object.
Example #2: Use DatetimeIndex.tz_localize() function to make the naive DatetimeIndex object to an object that is time zone aware.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here "D" represents calendar day frequency didx = pd.DatetimeIndex(start ="2014-08-01 10:05:45", freq ="D", periods = 5) # Print the DatetimeIndexprint(didx) |
Выход :
Now we want to convert the naive DatetimeIndex object into a timezone aware object
# make timezone awaredidx.tz_localize(tz ="US/Eastern") |
Выход :
Как видно из выходных данных, функция добавила информацию о часовом поясе в объект didx.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.