2015-08-24 47 views
0

我不熟悉Python,只是調試現有的代碼。我在這裏比較兩個日期,但他們有不同的格式。當我進行比較時,我得到了「TypeError:無法比較無偏移和無偏移的日期時間」。在Python中比較兩種不同格式的日期

if date_start <= current_date:

"TypeError: can't compare offset-naive and offset-aware

str(date_start) >> 2015-08-24 16:25:00+00:00

str(current_date) >> 2015-08-24 17:58:42.092391

如何進行有效的日期比較?我假設我需要將一個轉換爲另一種格式。

UPDATE

hour_offset = 0 
minute_offset = 0 
if timezone_offset: 
    offset_sign = int('%s1' % timezone_offset[0]) 
    hour_offset = offset_sign * int(timezone_offset[1:3]) 
    minute_offset = offset_sign * int(timezone_offset[3:5])  
    current_date = (datetime.datetime.now() + 
     datetime.timedelta(hours=hour_offset,minutes=minute_offset)) 

以前的開發可能已經應用了時區偏移這樣。對此有任何想法?

+1

http://stackoverflow.com/questions/3457452/comparing-dates-and-times-in-different-formats-using-python – chandu

+0

沒有代碼在這裏調試 – holdenweb

+0

對不起,讓我修改問題並添加附加代碼.. –

回答

1

這裏沒有更多的細節,solve.But,如果你想獲得一個offset-naive time.Try這

(offset-aware-datetime).replace(tzinfo=None) 

要一個時區添加到offset-naive time.Try這個

(offset-naive-datetime).replace(tzinfo=tz) 
+0

完美!謝謝! –

+1

如果時區不是utc,則會失敗 - 因爲您將更改時間的時間。 –

+0

@DouglasLeeder我同意你的意見。我目前正在嘗試不同的時區。 –

2

使用dt.replace(tzinfo=tz)將時區添加到天真的日期時間,以便它們可以進行比較。

1

一種方法是將日期轉換爲自時代以來的秒數,然後進行比較。說,如果你的日期是2015-08-24 16:25:00那麼你可以使用日期時間方法轉換爲秒。它的參數爲(year, month, day[, hour[, minute[,second[, microsecond[, tzinfo]]]]])。它返回一個日期時間對象。最後,您可以使用strftime()將秒作爲零填充十進制數。所以你的代碼可以是:

import datetime 
d1 = datetime.datetime(2015,8,24,16,25,0) 
d2 = datetime.datetime(2015,8,24,17,58,42,92391) 
if int(d1.strftime("%s")) > int(d2.strftime("%s")): 
    print "First one is bigger" 
else: 
    print "Second one is bigger" 

我希望這有助於!