国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2019-11-25 16:36:29
字體:
供稿:網(wǎng)友

前言

最近遇到了一個問題:我的serverclient不是在一個時區(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 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. 將時間轉(zhuǎn)換為秒,加上120秒,然后再轉(zhuǎn)換回標(biāo)準(zhǔn)格式:

#-*-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

總結(jié)

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 喀喇| 丹寨县| 光山县| 滨州市| 汝城县| 新乡县| 凌海市| 渝北区| 湟源县| 柯坪县| 墨江| 武汉市| 威信县| 随州市| 太湖县| 临城县| 九龙县| 胶南市| 龙胜| 句容市| 安顺市| 廊坊市| 瑞金市| 镇雄县| 迭部县| 伊金霍洛旗| 安多县| 罗平县| 响水县| 万盛区| 曲阜市| 双桥区| 灌云县| 洛扎县| 沂南县| 五寨县| 修武县| 临高县| 延庆县| 大余县| 通许县|