python - 如何通过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()
......
所以,我的主要问题是:
- 如何获取当前时间?
- 如何做减法和比较两个时间变量?
解决方案
timezone.now()
如果我没记错的话,你可以通过wheretimezone
是 django.utils 的一部分来获取当前时间。对于日期的操作,您可以使用
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...
推荐阅读
- c# - 试图能够通过透明度点击
- dictionary - 带有嵌套地图的 terraform 嵌套动态块
- excel - 从同一行的其他单元格获取值
- amazon-web-services - 如何在没有 IAM 的情况下从客户端下载 aws s3 文件,但只有 IP 限制?
- qt - Qt QML:转换着色器效果以用于新的 Direct3D 11 RHI
- c# - 意外字符“$”
- vmware-clarity - 我可以使用 Clarity 在堆栈视图中嵌套标题吗
- powerbi - 如何计算每月平均值,包括 Power BI 中没有记录的月份
- java - 如何在 JFrame 中组合图像?
- node.js - JavaScript堆内存不足-nodejs和邮递员