當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas Series.dt.tz_localize用法及代碼示例

Series.dt可用於以datetimelike的形式訪問序列的值並返回幾個屬性。 Pandas Series.dt.tz_localize()函數將tz-naive日期時間數組/索引本地化為tz-aware日期時間數組/索引。此方法采用時區(tz)天真的Datetime數組/索引對象,並使該時區可用。不會將時間移到另一個時區。

用法: Series.dt.tz_localize(*args, **kwargs)

參數:


tz:將時間戳轉換為的時區。

返回值:與自我同類型

範例1:采用Series.dt.tz_localize()函數將係列中的tz-naive日期時間值本地化為tz-aware。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', 
               '2010-1-1 09:25', '2019-12-31 00:00']) 
  
# Creating the index 
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] 
  
# set the index 
sr.index = idx 
  
# Convert the underlying data to datetime  
sr = pd.to_datetime(sr) 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.dt.tz_localize()函數將給定的tz-naive係列本地化為“美國/東部”。

# localize to 'US / Eastern' 
result = sr.dt.tz_localize(tz = 'US / Eastern') 
  
# print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.dt.tz_localize()函數已成功將給定的tz-naive日期時間序列本地化為tz-aware。

範例2:采用Series.dt.tz_localize()函數將給定的series對象作為本地python datetime對象的數組返回。


# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D')) 
  
# Creating the index 
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] 
  
# set the index 
sr.index = idx 
  
# Print the series 
print(sr)

輸出:

現在我們將使用Series.dt.tz_localize()函數將給定的tz-naive係列本地化為“歐洲/柏林”。

# localize to 'Europe / Berlin' 
result = sr.dt.tz_localize(tz = 'Europe / Berlin') 
  
# print the result 
print(result)

輸出:

正如我們在輸出中看到的,Series.dt.tz_localize()函數已成功將給定的tz-naive日期時間序列本地化為tz-aware。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Series.dt.tz_localize。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。