前言
最近遇到了一個(gè)問(wèn)題:我的server
和client
不是在一個(gè)時(shí)區(qū),server
時(shí)區(qū)是EDT,即美國(guó)東部時(shí)區(qū),client
,就是我自己的電腦,時(shí)區(qū)是中國(guó)標(biāo)準(zhǔn)時(shí)區(qū),東八區(qū)。處于測(cè)試需要,我需要向server
發(fā)送一個(gè)時(shí)間,使得server在這個(gè)時(shí)間戳去執(zhí)行一些動(dòng)作。這個(gè)時(shí)間戳通常是當(dāng)前時(shí)間加2分鐘或者幾分鐘。
通常美東在夏令時(shí)時(shí),和我們相差12小時(shí),所以直接減掉這12小時(shí),然后再加兩分鐘,可以實(shí)現(xiàn)發(fā)送基于server
的時(shí)間戳,但是只有一半時(shí)間是夏令時(shí),所以考慮還是基于時(shí)區(qū)來(lái)做。百度了一下,Python有一個(gè)模塊pytz
是時(shí)區(qū)相關(guān)的,但不是builtin
方法,所以需要安裝一下。
1. 首先安裝pytz,pip install pytz.
2. 試了一下水,打印出美國(guó)的時(shí)區(qū):
1
2
3
4
5
|
#-*-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'] |
這個(gè)地方還真多,不過(guò)既然是東部,直接選New York就好了。
3. 下一步,打印出美東的current time。
1
2
3
4
5
6
7
8
9
|
#-*-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. 將時(shí)間轉(zhuǎn)換為秒,加上120秒,然后再轉(zhuǎn)換回標(biāo)準(zhǔn)格式:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#-*-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
總結(jié)
以上就是在Python用模塊pytz來(lái)轉(zhuǎn)換時(shí)區(qū)的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)使用Python能有所幫助。