Python時間操作之pytz模塊使用詳解

前言

在我們日常生活中,時間概念常伴我們左右。讓我們簡單的回憶一下自己的一天,大致有以下時間點:

  • 8:00,清晨的陽光照射到床頭伴著鬧鐘,你從睡眠中清醒
  • 8:30,你洗漱完成換好工裝,出門上班
  • 9:00,準時坐到工位上,開始一天的工作
  • 12:00,吃午飯午休
  • 14:00,開始下午的工作
  • ….,時間無處不在,在我們日程計劃中占著標志flag的角色

假設,同事突然問你Moscow城市,現在幾點瞭啦。這時候我們要經過時區的換算的一系列麻煩的過程

有沒有更快的方法計算出指定時區的時間?—-答案肯定有

在學習Python過程中,我們已經瞭解瞭一些關於時間操作的庫,如:

  • Python內置庫:time,datatime,calendar,zoneinfo
  • 第三方庫:dateutil,pytz,arrow

關於Python時間操作內置庫,大傢可以訪問往期內容。本期,我們來重點學習一下pytz模塊的使用方法,Let's go~~

1. pytz 模塊概述

什麼是 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 模塊使用方法

由於pytz是第三方庫,因此我們在使用前需要使用pip進行下載其依賴庫

pip install pytz

代碼中使用時,我們需要使用import來進行導入

# 方式一:導入整個模塊
import pytz

# 方式二:導入具體的庫
from pytz import timezone

2. pytz 相關方法

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))

時區名獲取:

  • 時區名各式化:pytz.timezone(tzname)
  • 獲取所有的時區:pytz.country_timezones.values()
  • 獲取地區的代碼:pytz.country_timezones.keys()

3. pytz 時區查詢

根據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
---

4. pytz 日期計算

同理,我們日常生活中根據當地時間,算出對方所在時區的當地時間,思路與上述大致一樣。

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
---

總結

本期我們對時間操作的pytz模塊進行基本的瞭解和學習。pytz模塊可以幫助我們快速進行時區計算出時間,pytz模塊具有tzinfo特性。

到此這篇關於Python時間操作之pytz模塊使用詳解的文章就介紹到這瞭,更多相關Python pytz模塊內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: