Python時區轉換


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

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

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

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

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

這個地方還真多,不過既然是東部,直接選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. 將時間轉換為秒,加上120秒,然后再轉換回標准格式:

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

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM