亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python用模塊pytz來轉(zhuǎn)換時區(qū)

オリジナル 2017-01-16 15:44:04 413
サマリー:前言最近遇到了一個問題:我的server和client不是在一個時區(qū),server時區(qū)是EDT,即美國東部時區(qū),client,就是我自己的電腦,時區(qū)是中國標(biāo)準(zhǔn)時區(qū),東八區(qū)。處于測試需要,我需要向server發(fā)送一個時間,使得server在這個時間戳去執(zhí)行一些動作。這個時間戳通常是當(dāng)前時間加2分鐘或者幾分鐘。通常美東在夏令時時,和我們相差12小時,所以直接減掉這12小時,然后再加兩分鐘,可以實(shí)現(xiàn)發(fā)送

前言

最近遇到了一個問題:我的server和client不是在一個時區(qū),server時區(qū)是EDT,即美國東部時區(qū),client,就是我自己的電腦,時區(qū)是中國標(biāo)準(zhǔn)時區(qū),東八區(qū)。處于測試需要,我需要向server發(fā)送一個時間,使得server在這個時間戳去執(zhí)行一些動作。這個時間戳通常是當(dāng)前時間加2分鐘或者幾分鐘。

通常美東在夏令時時,和我們相差12小時,所以直接減掉這12小時,然后再加兩分鐘,可以實(shí)現(xiàn)發(fā)送基于server的時間戳,但是只有一半時間是夏令時,所以考慮還是基于時區(qū)來做。百度了一下,Python有一個模塊pytz是時區(qū)相關(guān)的,但不是builtin方法,所以需要安裝一下。

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

2. 試了一下水,打印出美國的時區(qū):

#-*-coding:utf-8-*-
#/usr/bin/env python
import pytz
print(pytz.country_timezones('us'))#['
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. 將時間轉(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

總結(jié)

以上就是在Python用模塊pytz來轉(zhuǎn)換時區(qū)的全部內(nèi)容,希望本文的內(nèi)容對大家學(xué)習(xí)使用Python能有所幫助。

更多關(guān)于Python用模塊pytz來轉(zhuǎn)換時區(qū)請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章! 

手記を発表する

人気のある見出し語