[英]Python check if date is within 24 hours
I have been trying some code for this, but I can't seem to completely wrap my head around it.我一直在为此尝试一些代码,但我似乎无法完全理解它。
I have a set date, set_date
which is just some random date as you'd expect and that one is just data I get.我有一个设定的日期,
set_date
这只是一些你期望的随机日期,而那个只是我得到的数据。 Now I would like some error function that raises an error if datetime.now()
is within 24 hours of the set_date
.现在我想要一些错误函数,如果
datetime.now()
在set_date
24 小时内会引发错误。
I have been trying code with the timedelta(hours=24)
我一直在尝试使用
timedelta(hours=24)
编写代码
from datetime import datetime, timedelta
now = datetime.now()
if now < (set_date - timedelta(hours=24)):
raise ValidationError('')
I'm not sure whats right to do with this, what the good way to do is.我不确定这样做的正确方法是什么,这样做的好方法是什么。 How exactly do I check if the current time is 24 hours before the set date?
我如何确切地检查当前时间是否在设定日期之前 24 小时?
Like that?像那样?
if now-timedelta(hours=24) <= set_date <= now:
... #date less than 24 hours in the past
If you want to check for the date to be within 24 hours on either side:如果您想检查日期是否在任一侧的 24 小时内:
if now-timedelta(hours=24) <= set_date <= now+timedelta(hours=24):
... #date within 24 hours
To check if the date is within 24 hours.检查日期是否在 24 小时内。
Take a difference between the current time and the past time and check if the no.取当前时间和过去时间之间的差异,并检查是否为否。 of days is zero.
天数为零。
past_date = datetime(2018, 6, 6, 5, 27, 28, 369051)
difference = datetime.utcnow() - past_date
if difference.days == 0:
print "date is within 24 hours"
## Also you can check the difference between two dates in seconds
total_seconds = (difference.days * 24 * 60 * 60) + difference.seconds
# Edited. Also difference have in-built method which will return the elapsed seconds.
total_seconds = difference.total_seconds()
You can check if total_seconds is less than the desired time您可以检查 total_seconds 是否小于所需时间
That will do:这样做:
if now - timedelta(hours=24) <= set_date <= now + timedelta(hours=24):
#Do something
Which is equivalent to:这相当于:
if now - timedelta(hours=24) <= set_date <= now or now <= set_date <= now + timedelta(hours=24):
# ---^--- in the past 24h ---^--- in the future 24h
#Do something
It is as simple as that:就这么简单:
from datetime import datetime
#...some code...
if (datetime.now() - pastDate).days > 1:
print('24 hours have passed')
else:
print('Date is within 24 hours!')
What you do here is subtract the old date pastDate
from the current date datetime.now()
, which gives you a time delta datetime.timedelta(...)
object.你在这里做的是从当前日期
datetime.now()
减去旧日期pastDate
,这给你一个时间增量datetime.timedelta(...)
对象。 This object stores the number of days, seconds and microseconds which have passed since the old date.此对象存储自旧日期以来经过的天数、秒数和微秒数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.