2013-04-04 100 views
1

我所遇到下面的代碼:utc在utc時間戳記上做了什麼?

datetime.datetime.utcnow().replace(tzinfo=tzutc()) 

我什麼也看不見替換()調用是幹什麼的,從閱讀似乎把它轉換成一個UTC時間戳的文件 - 但肯定utcnow()會返回一個UTC時間戳。

回答

2
datetime.datetime.utcnow() 
# returns datetime.datetime(2013, 4, 4, 10, 39, 1, 303329) 

爲您提供了UTC的當前日期時間不tzinfo信息:

.replace(tzinfo=tzutc()) 
# returns datetime.datetime(2013, 4, 4, 10, 39, 1, 303329, tzinfo=<UTC>) 

會將此tzinfo信息到datetime對象。

可以使用得到相同的(與UTC tzinfo UTC當前日期時間):

datetime.datetime.now(pytz.utc) 
# returns datetime.datetime(2013, 4, 4, 10, 39, 1, 303329, tzinfo=<UTC>) 
0

這只是調用datetime.replace(),這個特定的用法在該文檔頁面上提到很多。

這是有用的,因爲datetime.datetime.utcnow()返回datetime沒有時區信息(tzinfoNone):在replace()調用來改變這種狀況。