2008-08-22 15 views
3
>>> import time 
>>> time.strptime("01-31-2009", "%m-%d-%Y") 
(2009, 1, 31, 0, 0, 0, 5, 31, -1) 
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 
1233378000.0 
>>> 60*60*24 # seconds in a day 
86400 
>>> 1233378000.0/86400 
14275.208333333334 

time.mktime應該返回自紀元以來的秒數。既然我在午夜時分給它一個時間,並且這個時代是在午夜時分,那麼結果是否可以被一天中的秒數整除?使用time.mktime進行日期/時間轉換似乎是錯誤的

+1

不知道這是你的問題,但知道time.mktime調用本地時間,它咬了我一次或兩次屁股。 – sparkes 2008-08-22 09:13:28

回答

3
mktime(...) 
    mktime(tuple) -> floating point number 

    Convert a time tuple in local time to seconds since the Epoch. 

當地時間...看中了這一點。

的時間元組:

The other representation is a tuple of 9 integers giving local time. 
The tuple items are: 
    year (four digits, e.g. 1998) 
    month (1-12) 
    day (1-31) 
    hours (0-23) 
    minutes (0-59) 
    seconds (0-59) 
    weekday (0-6, Monday is 0) 
    Julian day (day in the year, 1-366) 
    DST (Daylight Savings Time) flag (-1, 0 or 1) 
If the DST flag is 0, the time is given in the regular time zone; 
if it is 1, the time is given in the DST time zone; 
if it is -1, mktime() should guess based on the date and time. 

順便提及,我們似乎是分開6小時:

>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 
1233356400.0 
>>> (1233378000.0 - 1233356400)/(60*60) 
6.0 
0

有趣。我不知道,但我確實嘗試過:

>>> now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1)) 
>>> tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1)) 
>>> tomorrow - now 
86400.0 

這是您的預期。我猜?也許從時代開始就進行了一些修正。這可能只有幾秒鐘,就像閏年一樣。我想我以前聽過類似的東西,但不記得具體是怎麼完成的......

7

簡答:因爲時區。

時代以UTC。

例如,我在IST(愛爾蘭標準時間)或UTC + 1上。 time.mktime()是相對於我的時區,所以我的系統上這是指

>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 
1233360000.0 

因爲你得到的結果1233378000,那就表明,你在我身後5小時

>>> (1233378000 - 1233360000)/(60*60)  
5 

看一看使用UTC的time.gmtime()函數。

2

菲爾的答案真的解決了它,但我會詳細說明一點。由於時代是UTC,如果我想將其他時間與時代進行比較,我需要將它們解釋爲UTC。

>>> calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 
1233360000 
>>> 1233360000/(60*60*24) 
14275 

到時候的元組轉換爲時間戳治療是UTC時間,我得到了一些這按秒一天數整除。

我可以使用它將日期轉換爲從最初的日期代表,這是我最終以後。