這篇文章主要講解了“Python時間操作之pytz模塊如何使用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Python時間操作之pytz模塊如何使用”吧!
pytz 模塊是依賴Olson tz數據庫導入的,它支持直接使用時區名進行時間計算
pytz 模塊涉及時區,因此其也指定tzinfo信息(詳情可見datetime.tzinfo)
pytz 模塊通常與datetime模塊結合一起使用,返回具體的時間名
pytz 模塊可以解決夏令時結束時不明確的問題
重要說明:
pytz 模塊支持大多數的時區計算,使用IANA的數據接口,CLDR(Unicode 語言環境)項目提供翻譯
本地還需要按照依賴是時區映射表tzdata數據庫(pip install tzdata)
國家/城市代碼映射表,pytz庫中存儲在_CountryTimezoneDict()字典中

我們可以通過 pytz.country_timezones常量來獲取code,timezon
<pytz._CountryTimezoneDict object at 0x00000256FBE52E30>
由于pytz是第三方庫,因此我們在使用前需要使用pip進行下載其依賴庫
pip install pytz
代碼中使用時,我們需要使用import來進行導入
# 方式一:導入整個模塊 import pytz # 方式二:導入具體的庫 from pytz import timezone
pytz 模塊包含國家碼查詢、時區名等方法
創建本地化時間:
方式一:pytz.timezone(tzname).localise()
tz = pytz.timezone('US/Eastern')
local_time =tz.localize(datetime.datetime(2022, 6, 13,23, 0, 0))
print(local_time)方式二:local_time.astimezone(tzname)
ast = local_time.astimezone(tz)
方式三:tz.normzlize()處理夏令時
nor = tz.normzlize(datetime.datetime(2022, 6, 13,23, 0, 0))
時區名獲?。?/p>
時區名各式化:pytz.timezone(tzname)
獲取所有的時區:pytz.country_timezones.values()
獲取地區的代碼:pytz.country_timezones.keys()
根據pytz模塊相關方法,我們可以寫一個函數來實現場景:
輸入一個城市:city,如"Simferopol"
輸出城市的時區偏離量:如+3
實現思路,大致如下:
首先調用pytz.country_timezones.values()獲取到所有的時區timezones
使用split()將時區的城市名進行分割形成列表city_list
先在city_list.index[city]找到City_index
然后根據City_index在timezones找到時區tzname
pytz.timezone(tzname)格式化,算出標準時間
import pytz
from datetime import datetime
def timezon_city_gmt(city):
timezons = sum(list(pytz.country_timezones.values()),[])
cityList = [city.split("/")[1] for city in timezons]
city_index = cityList.index(city)
tz = pytz.timezone(timezons[city_index])
gmt = "GMT" + str(datetime.now().astimezone(tz))[-6:]
return gmt
print(timezon_city_gmt("Simferopol"))
---
GMT+03:00
---同理,我們日常生活中根據當地時間,算出對方所在時區的當地時間,思路與上述大致一樣。
datetime.strptime()將時間字符串轉化成datetime對象
import pytz
from datetime import datetime
def update_datetime_tz(olddatetime, city, formate):
timezons = sum(list(pytz.country_timezones.values()), [])
cityList = [city.split("/")[1] for city in timezons]
city_index = cityList.index(city)
tz = pytz.timezone(timezons[city_index])
datetime_type = datetime.strptime(olddatetime, formate)
newdatetime = datetime_type.astimezone(tz)
return newdatetime.strftime(str(formate))
print(update_datetime_tz("2022-06-13 12:46:03","Moscow","%Y-%m-%d %H:%M:%S"))
---
2022-06-13 07:46:03
---感謝各位的閱讀,以上就是“Python時間操作之pytz模塊如何使用”的內容了,經過本文的學習后,相信大家對Python時間操作之pytz模塊如何使用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。