【问题标题】:Python check that the date is 30 days in the futurePython 检查日期是否为未来 30 天
【发布时间】:2014-02-21 23:41:51
【问题描述】:

我想编写一个测试,从保存的对象recipient.expiry_date 中提取时间,并检查日期是否为未来 30 天。

这是我尝试过的:

days_to_match = timezone.now() + timedelta(days=30)

self.assertEqual(recipient.expiry_date, days_to_match)

因为它还包含不匹配的时间。

如何做到这一点?

请注意,recipient.expiry_date 是在我的模型中使用timezone.now()设置的,所以比较来自 python 的日期似乎是错误的。

【问题讨论】:

    标签: python


    【解决方案1】:

    正如您在this SO answer 中看到的,您可以使用date() 仅比较日期而不比较时间。或者你可以把时间数据=0。

    self.assertEqual(recipient.expiry_date.date(), days_to_match.date())
    

    【讨论】:

      【解决方案2】:

      你可以只看日期部分:

      self.assertEqual(recipient.expiry_date.year, days_to_match.year)
      self.assertEqual(recipient.expiry_date.month, days_to_match.month)
      self.assertEqual(recipient.expiry_date.day, days_to_match.day)
      

      【讨论】:

        猜你喜欢
        • 2011-12-26
        • 2010-10-06
        • 2017-02-09
        • 2011-10-31
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 1970-01-01
        • 2019-12-29
        相关资源
        最近更新 更多