簡體   English   中英

在Python中比較兩個日期的不同格式

[英]Compare two dates with different formats in Python

我不熟悉Python,只是調試現有代碼。 我在這里比較兩個日期,但它們具有不同的格式。 當我進行比較時,出現“ TypeError:無法比較天真的偏移時間和知道偏移的日期時間”。

if date_start <= current_date:

“ TypeError:無法比較原生偏移量和感知偏移量

str(date_start) >> 2015-08-24 str(date_start) + 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))

以前的開發人員可能已經以這種方式應用了時區偏移。 對這個有什么想法嗎?

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

這里沒有更多的要解決的細節,但是如果您想獲得offset-naive嘗試此

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

要將時區添加到offset-naive的時區。

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

一種方法是將日期轉換為自紀元以來的秒數,然后進行比較。 例如,如果您的日期是2015-08-24 16:25:00那么您可以使用datetime方法將其轉換為秒。 它采用的參數為(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"

我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM