首页 > 解决方案 > 如何通过python django计算时间变量并将时间数据与当前时间进行比较?

问题描述

例如,我在 models.py 中有一个模型,如下所示:

class BlackList(models.Model):
    username = models.CharField(max_length=1000)
    flag1 = models.BooleanField(default=False)
    trytologintime = models.DateTimeField(auto_now_add=True, null=True)

在views.py中,我尝试做的是这样的:

......    
username = request.POST.get('username')  # Get username input first
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
black_list_user = BlackList.objects.get(username=username)
# timenow = get time for now ( I do not know how to get it foe now )
passtime = timenow-black_list_user.trytologintime (Also do not know how to do the subtraction for time variable)
     if passtime > 24 hr (How to compare the time)
        black_list_user.flag1 = True
        black_list_user.save()
......

所以,我的主要问题是:

  1. 如何获取当前时间?
  2. 如何做减法和比较两个时间变量?

标签: pythondjangotime

解决方案


  1. timezone.now()如果我没记错的话,你可以通过wheretimezone是 django.utils 的一部分来获取当前时间。

  2. 对于日期的操作,您可以使用timedelta, 的一部分datetime

例如,要将日期移到未来 24 小时:

current_time = timezone.now()
tomorrow = current_time + timedelta(hours=24)

您还可以按预期比较日期。所以在你的例子中:

last_login_time = disalloweduser.try_to_login_time
if last_login_time + timedelta(hours=24) > timezone.now():
    etc...

推荐阅读