【问题标题】:Compare two dates with different formats in Python在 Python 中比较两个不同格式的日期
【发布时间】:2015-08-24 10:11:51
【问题描述】:

我不熟悉 Python,只是调试现有代码。我在这里比较两个日期,但它们有不同的格式。当我进行比较时,我得到“TypeError: can't compare offset-naive and offset-aware datetimes”。

if date_start <= current_date:

"TypeError: 无法比较 offset-naive 和 offset-aware

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

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

如何进行有效的日期比较?我假设我需要将一种格式转换为另一种格式。

更新

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))

以前的开发人员可能已经以这种方式应用了时区偏移。对这个有什么想法吗?

【问题讨论】:

  • 这里没有要调试的代码
  • 对不起,让我修改问题并添加附加代码..
  • 这两个日期时间是否来自同一个位置?如果不是,那么就没有明智的方法来比较原始的偏移日期时间和偏移感知的日期时间。
  • @PM2Ring:让我向您展示有关 current_date 是如何得出的代码。我要更新问题。

标签: python django


【解决方案1】:

使用dt.replace(tzinfo=tz) 将时区添加到原始日期时间,以便可以比较它们。

【讨论】:

    【解决方案2】:

    这里没有更多细节需要解决。但是如果你想得到一个offset-naive时间。试试这个

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

    要将时区添加到offset-naive time。试试这个

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

    【讨论】:

    • 如果时区不是 UTC,那将失败 - 因为您将更改 timedate 上的时间。
    • @DouglasLeeder 我同意你的看法。我目前正在尝试不同的时区。
    • @DouglasLeeder 更新了答案(从你那里复制:p)
    【解决方案3】:

    一种方法是将日期转换为自纪元以来的秒数,然后进行比较。比如说,如果您的日期是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"
    

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 2020-08-16
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多