前言
最近遇到了一個問題:我的
server
和
client
不是在一個時區,
server
時區是EDT,即美國東部時區,
client
,就是我自己的電腦,時區是中國標準時區,東八區。處于測試需要,我需要向
server
發送一個時間,使得server在這個時間戳去執行一些動作。這個時間戳通常是當前時間加2分鐘或者幾分鐘。
通常美東在夏令時時,和我們相差12小時,所以直接減掉這12小時,然后再加兩分鐘,可以實現發送基于
server
的時間戳,但是只有一半時間是夏令時,所以考慮還是基于時區來做。百度了一下,Python有一個模塊
pytz
是時區相關的,但不是
builtin
方法,所以需要安裝一下。
1. 首先安裝pytz,pip install pytz.
2. 試了一下水,打印出美國的時區:
#-*-coding:utf-8-*- #/usr/bin/env python import pytz print(pytz.country_timezones('us'))#[u'America/New_York', u'America/Detroit', u'America/Kentucky/Louisville', u'America/Kentucky/Monticello', u'America/Indiana/Indianapolis', u'America/Indiana/Vincennes', u'America/Indiana/Winamac', u'America/Indiana/Marengo', u'America/Indiana/Petersburg', u'America/Indiana/Vevay', u'America/Chicago', u'America/Indiana/Tell_City', u'America/Indiana/Knox', u'America/Menominee', u'America/North_Dakota/Center', u'America/North_Dakota/New_Salem', u'America/North_Dakota/Beulah', u'America/Denver', u'America/Boise', u'America/Phoenix', u'America/Los_Angeles', u'America/Anchorage', u'America/Juneau', u'America/Sitka', u'America/Metlakatla', u'America/Yakutat', u'America/Nome', u'America/Adak', u'Pacific/Honolulu']
這個地方還真多,不過既然是東部,直接選New York就好了。
3. 下一步,打印出美東的current time。
#-*-coding:utf-8-*- #/usr/bin/env python import pytz import time import datetime tz = pytz.timezone('America/New_York') a = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") print(a)
#2016-08-18 02:26:53
4. 將時間轉換為秒,加上120秒,然后再轉換回標準格式:
#-*-coding:utf-8-*- #/usr/bin/env python import pytz import time import datetime print(pytz.country_timezones('us')) tz = pytz.timezone('America/New_York') a = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") print(a) b=time.mktime(time.strptime(a,'%Y-%m-%d %H:%M:%S'))+int(2)*60 print(time.strftime("%Y-%m-%d %H:%M",time.localtime(b)))
#2016-08-18 02:28
總結
以上就是在Python用模塊pytz來轉換時區的全部內容,希望本文的內容對大家學習使用Python能有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
