2014-02-28 87 views

回答

1

要轉換樸素的日期時間對象噸,它表示時間UTC不同時區:

from datetime import datetime 
import pytz 

tz = pytz.timezone('US/Eastern') #NOTE: deprecated timezone name 

naive_utc_dt = datetime.utcnow()    # naive datetime object 
utc_dt = naive_utc_dt.replace(tzinfo=pytz.utc) # aware datetime object 
east_dt = utc_dt.astimezone(tz)     # convert to Eastern timezone 
naive_east_dt = east_dt.replace(tzinfo=None) #XXX use it only if you have to 

注意:如果源的時區不是UTC然後.localize(),應當使用.normalize()方法。

pytz允許您處理給定區域的utc偏移更改(不僅僅是由於DST):今天,過去(很多庫在這裏失敗)。

+0

哈!我*只是*提出了相同的解決方案!謝謝! –

+0

但我需要結果作爲本地日期時間來與pymongo一起工作(請參閱我的回答) –

+0

@SeanW .:如果必須,可以剝離時區信息。我已經更新了答案 – jfs

0

經過多一點護目鏡,我發現this question,這導致我的答案。

  1. 將UTC時區的本地UTC日期時間
  2. 將其轉換成東部時間
  3. 獲得UTC的該偏移作爲timedelta
  4. 補充一點,原來的日期時間
ET = pytz.timezone("America/New_York") 

def utc_to_et(utcdt): 
    utc_with_tz = utcdt.replace(tzinfo=pytz.UTC) 
    offset = utc_with_tz.astimezone(ET).utcoffset() 
    return utcdt + offset 
0

另外請注意,如果Mongo連接沒有以時區知道的方式打開,那麼您只需要將天真的日期時間從數據庫中取出即可。

from pymongo import Connection 
# Create a timezone aware connection 
connection = Connection('localhost', 27017, tz_aware=True) 
相關問題