[英]Compare two dates with different formats in Python
I'm not familiar with Python, just debugging an existing code. 我不熟悉Python,只是调试现有代码。 I'm comparing two dates here but they have different formats.
我在这里比较两个日期,但它们具有不同的格式。 I get the "TypeError: can't compare offset-naive and offset-aware datetimes" when I do the compare.
当我进行比较时,出现“ TypeError:无法比较天真的偏移时间和知道偏移的日期时间”。
if date_start <= current_date:
"TypeError: can't compare offset-naive and offset-aware
“ TypeError:无法比较原生偏移量和感知偏移量
str(date_start)
>> 2015-08-24 16:25:00+00:00str(date_start)
>> 2015-08-24str(date_start)
+ 00:00
str(current_date)
>> 2015-08-24 17:58:42.092391str(current_date)
>> 2015-08-24 17:58:42.092391
How do I make a valid date comparison? 如何进行有效的日期比较? I'm assuming I need to convert one to another format.
我假设我需要将一种转换为另一种格式。
UPDATE 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))
The previous dev might have applied the timezone offset this way. 以前的开发人员可能已经以这种方式应用了时区偏移。 Any thoughts on this one?
对这个有什么想法吗?
使用dt.replace(tzinfo=tz)
将时区添加到原始日期时间,以便可以进行比较。
There is no more details here to solve.But if you want to get a offset-naive
time.Try this 这里没有更多的要解决的细节,但是如果您想获得
offset-naive
尝试此
(offset-aware-datetime).replace(tzinfo=None)
To add a timezone to offset-naive
time.Try this 要将时区添加到
offset-naive
的时区。
(offset-naive-datetime).replace(tzinfo=tz)
One way is to convert the date to seconds since epoch and then compare. 一种方法是将日期转换为自纪元以来的秒数,然后进行比较。 Say,if your date is
2015-08-24 16:25:00
then you can convert to seconds using datetime method. 例如,如果您的日期是
2015-08-24 16:25:00
那么您可以使用datetime方法将其转换为秒。 It takes parameters as (year, month, day[, hour[, minute[,second[, microsecond[, tzinfo]]]]])
. 它采用的参数为
(year, month, day[, hour[, minute[,second[, microsecond[, tzinfo]]]]])
。 It returns a datetime object. 它返回一个日期时间对象。 Finally, you can use strftime() to get seconds as a zero-padded decimal number.
最后,您可以使用strftime()将秒作为填充零的十进制数字。 So your code can be:
因此,您的代码可以是:
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"
I hope this helps! 我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.