2014-11-16 324 views
0

我有一個date_object.time(),它的Asia/Taipei時間python將時間轉換爲utc時間?

date_object.time() = '10:00:00' 

我也得到了datetime.datetime.now與時區Asia/Taipei

current = datetime.datetime.now(pytz.utc) 
taipeitime = current.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Taipei')) 

然後,我結合date_object.time()taipeitime

combine = datetime.datetime.combine(taipeitime, date_object.time()) #Asia/Taipei time 

而且我有轉換combine UTC時間 但我得到的錯誤:

print combine.astimezone(pytz.utc) 
ValueError: astimezone() cannot be applied to a naive datetime 

請教我如何轉換呢?謝謝

回答

0

的日期時間的。時間()方法失去的時區信息,使用.timetz(),而不是如:

>> combine = datetime.datetime.combine(taipeitime, taipeitime.timetz()) 
>> combine.astimezone(pytz.utc) 

datetime.datetime(2014, 11, 16, 15, 13, 46, 948201, tzinfo=<UTC>) 

VS

>> combine = datetime.datetime.combine(taipeitime, taipeitime.time()) 
>> combine.astimezone(pytz.utc) 

Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
ValueError: astimezone() cannot be applied to a naive datetime 

看到https://docs.python.org/2/library/datetime.html#datetime.datetime.timetz

也可以將時區替換爲時間對象,例如,

combine = datetime.datetime.combine(taipeitime, 
        taipeitime.time().replace(tzinfo=pytz.timezone('Asia/Taipei'))) 

會給你一個時區知道結合時間。見https://docs.python.org/2/library/datetime.html#datetime.time.replace