1. 程式人生 > >python時區設置——pytz模塊

python時區設置——pytz模塊

normalize module str rac needed sub ont 網站 abstract

如果你的程序要考慮時區,可以使用pytz。datetime模塊中有tzinfo相關的東西,但是它是一個抽象類,文檔上說:

tzinfo is an abstract base clase, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime

module does not supply any concrete subclasses of tzinfo.

上面是說tzinfo是一個抽象類,不應該被直接實例化。你需要派生子類,提供相應的標準方法。datetime模塊並不提供tzinfo的任何子類。

所以你可能會使用pytz這個模塊。通過easy_install可以安裝。目前它的最新文檔在這裏。

關於時區使用的幾點想法:

1. 如果你的網站可能有來自其它時區的,可能你要考慮這個問題。都是一個地區的話,還要看服務器是否與用戶在一個地區,如果不在,也要考慮。
2. 因此,基本上要考慮服務器時區與用戶時區。服務器時區可以配置在系統中,全局生效。而用戶時區則與用戶相關,可以由用戶自已進行設置。
3. 在生成相關時間對象時要加入時區的信息,並在輸出時進行合適的轉換。

1.Localtime轉化為UTC時間

end_time = pytz.UTC.normalize(end_time)

2.從無時區的datetime轉換成有時區的(轉化後的時間= 原時間 + 時區)

context_tz = pytz.timezone(tz_name)
context_tz.localize(planned_time_no_zone)

python時區設置——pytz模塊