Python用模組pytz來轉換時區,pythonpytz

來源:互聯網
上載者:User

Python用模組pytz來轉換時區,pythonpytz

前言

最近遇到了一個問題:我的serverclient不是在一個時區,server時區是EDT,即美國東部時區,client,就是我自己的電腦,時區是中國標準時區,東八區。處於測試需要,我需要向server發送一個時間,使得server在這個時間戳記去執行一些動作。這個時間戳記通常是目前時間加2分鐘或者幾分鐘。

通常美東在夏令時時,和我們相差12小時,所以直接減掉這12小時,然後再加兩分鐘,可以實現發送基於server的時間戳記,但是只有一半時間是夏令時,所以考慮還是基於時區來做。百度了一下,Python有一個模組pytz是時區相關的,但不是builtin方法,所以需要安裝一下。

1. 首先安裝pytz,pip install pytz.

2. 試了一下水,列印出美國的時區:

#-*-coding:utf-8-*-#/usr/bin/env pythonimport pytzprint(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 pythonimport pytzimport timeimport datetimetz = 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 pythonimport pytzimport timeimport datetimeprint(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)*60print(time.strftime("%Y-%m-%d %H:%M",time.localtime(b)))

#2016-08-18 02:28

總結

以上就是在Python用模組pytz來轉換時區的全部內容,希望本文的內容對大家學習使用Python能有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.