純python處理時區的轉換
首先要明白python的datetime物件有兩種型別,而Python的datetime可以處理2種類型的時間,分別為offset-naive和offset-aware。前者是指沒有包含時區資訊的時間,後者是指包含時區資訊的時間,只有同類型的時間才能進行減法運算和比較。
#-*- coding=cp936 -*- from datetime import timedelta,tzinfo import datetime ZERO_TIME_DELTA = timedelta(0) LOCAL_TIME_DELTA = timedelta(hours=8) # 本地時區偏差 class UTC(tzinfo): """實現了格林威治的tzinfo類""" def utcoffset(self, dt): return ZERO_TIME_DELTA def dst(self, dt): return ZERO_TIME_DELTA class LocalTimezone(tzinfo): """實現北京時間的類""" def utcoffset(self, dt): return LOCAL_TIME_DELTA def dst(self, dt): return ZERO_TIME_DELTA def tzname(self, dt): #tzname需要返回時區名 return '+08:00' print datetime.datetime.now(UTC()) #UTC時間 差八個小時 print datetime.datetime.now(LocalTimezone()) #根據本地 時區 生成offset-aware類的datetime物件 print type(datetime.datetime.now(LocalTimezone())) print datetime.datetime.now() #北京時間 一旦生成了一個offset-naive型別的datetime物件 print datetime.datetime.now().replace(tzinfo=UTC()) # 呼叫replace(tzinfo=UTC())即可轉換成offset-aware型別 print datetime.datetime.now().replace(tzinfo=LocalTimezone()).astimezone(UTC()) #時區轉換, print '----------------------------------------------' print datetime.datetime.utcnow() #講一個 已知時區的datetime類轉換成UTC()的日期 datetime_test = datetime.datetime(2013,10,23,20,44,11).replace(tzinfo=LocalTimezone()).astimezone(UTC()) print datetime_test print '---------------------------------'
結果:
2014-02-19 07:38:07.328000+00:00
2014-02-19 15:38:07.328000+08:00
<type 'datetime.datetime'>
2014-02-19 15:38:07.328000
2014-02-19 15:38:07.328000+00:00
2014-02-19 07:38:07.328000+00:00
----------------------------------------------
2014-02-19 07:38:07.328000
2013-10-23 12:44:11+00:00
---------------------------------