[英]Compare two dates with different formats in Python
我不熟悉Python,只是调试现有代码。 我在这里比较两个日期,但它们具有不同的格式。 当我进行比较时,出现“ TypeError:无法比较天真的偏移时间和知道偏移的日期时间”。
if date_start <= current_date:
“ TypeError:无法比较原生偏移量和感知偏移量
str(date_start)
>> 2015-08-24str(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.