【问题标题】:How can I compare 3 dates using Django?如何使用 Django 比较 3 个日期?
【发布时间】:2020-09-05 16:55:30
【问题描述】:

我想比较 3 个日期以了解讲座是否开始。为此,我创建了 3 个属性,即 Lecture_start_date、lecture_finish_date 和当前日期。但是当我比较它们时,我得到一个错误,例如 strptime() argument 1 must be str, not DeferredAttribute 但我的 Lecture.l_date 也是字符串。

这是我的作品

def about(request,pk_test):
    classes = Classroom.objects.get(classroom_name=pk_test)
    department = Department.objects.all()
    ads= Ads.objects.all()
    student=Student.objects.all()
    lectures = Lecture.objects.all()
    mydate = datetime.today()
    lecture_start_date = datetime.strptime(Lecture.l_date, '%Y-%m-%`enter code here`d %H:%M:%S')
    lecture_finish_date = datetime.strptime(Lecture.l_date_end, '%Y-%m-%d %H:%M:%S')
    if mydate > lecture_start_date and mydate < lecture_finish_date :
         print("The lecture has been started.")

总之,我想根据我的当地时间找到讲座是否开始。为了找到我的当地时间,我使用了 mydate = datetime.today() 并且我有来自我的数据库的讲座开始时间和讲座和时间。我该如何比较那些?

【问题讨论】:

  • Lecture.1_date 是什么?
  • 对不起,我没有提到。 Lecture.l_date 是来自数据库的讲座开始日期。这是一个 DateTimeField。
  • @Codeisacode 如果讲座没有开始就没有结束,这不是真的吗?因为lecture_finish_date 的时间大于lecture_start_date。关键是如果您想检查讲座是否开始,您需要将mydatelecture_start_date 进行比较。对于错误,这是因为您返回的对象可能不是字符串类型。我希望这会有所帮助。Lecture.l_dateLecture.l_date_end 不是字符串。

标签: python django sqlite django-models django-views


【解决方案1】:

您需要注意调用Lecture.l_date,如果这是您数据库中的一列,您应该从特定记录中获取值,而不是作为类属性获取。

如果你想从类中获取 l_date,我建议你在 Lecture 中添加一个类方法,以便能够得到你想要比较的值。

您可以通过添加到您的模型中来实现此目的:

@classmethod
def get_l_date(cls):
    # Do the calculations you need to do
    return calculated_date

datetime.strptime - 需要一个字符串作为调用的第一个参数,这不是你现在传递的,如果你使用我之前建议的方法,你甚至不需要这个调用来转换成日期时间,并且会能够进行您正在寻找的比较。

【讨论】:

  • 感谢您的帮助。我明白了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 2011-01-13
相关资源
最近更新 更多