最近遇到了一個(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ū):
#-*-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。
#-*-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)格式:
#-*-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來(lái)轉(zhuǎn)換時(shí)區(qū)相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!
Copyright ? 2019- 91gzw.com 版權(quán)所有 湘ICP備2023023988號(hào)-2
違法及侵權(quán)請(qǐng)聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬(wàn)商天勤律師事務(wù)所王興未律師提供法律服務(wù)