2015-10-05 28 views
0

我想序列datetimejson但串行化之前,我需要當地時間轉換成UTC時間我怎麼能做到這一點,如果我知道tzinfo如何在序列化之前在Python中將本地日期時間轉換爲utcdatetime?

import datetime 

def some_conversion(d): 
    ??? 

# assume that now() and utcnow() is taken in same time - this code is not valid to test it. 
assert(some_conversion(datetime.datetime.now()) == datetime.datetime.utcnow()) 

我準備了一些序列化函數,但不知道如何解決轉換。我想以非常高的速度和全精度以utc格式序列化datetime

import datetime 
import json 
import timeit 

d = datetime.datetime.utcnow() 

def date_tuple(): 
    x = (d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond) 
    y = json.dumps(x) 
    z = json.loads(y) 
    b = datetime.datetime(*z) 

print timeit.timeit(date_tuple, number=1000) 

如果d = B: 提高ValueError異常(d-B)

回答

0

你試過pytz模塊?

假設你有符拉迪沃斯託克時區。

import pytz, datetime 
local = pytz.timezone("Asia/Vladivostok") 
naive_dt = datetime.datetime.now() 
local_dt = local.localize(naive_dt, is_dst=None) 
utc_dt = local_dt.astimezone (pytz.utc) 

還要檢查this問題

相關問題