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.
Now I would like some error function that raises an error if datetime.now() is within 24 hours of the set_date.
I have been trying code with the 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?
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:
if now-timedelta(hours=24) <= set_date <= now+timedelta(hours=24):
... #date within 24 hours
To check if the date is within 24 hours.
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
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. This object stores the number of days, seconds and microseconds which have passed since the old date.
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
Related
I expect that if I substract two datetimes in Python, I'll get datetime with substracted days, weeks, etc...
Here is my sample. What I get are just substracted hours, minutes and seconds. Date variable is taken from database. On type() function returns datetime.datetime.
def elapsed_time(date):
"""
Custom filter that format time to "x time age".
:param date:
:return:
"""
if date is None:
return 'No time given'
now = datetime.datetime.now()
elapsed = (now - date).seconds
if elapsed < 60:
return '{} seconds ago'.format(elapsed)
elif elapsed < 3600:
return '{} minutes ago'.format(int(elapsed / 60))
elif elapsed < 86400:
return '{} hours ago'.format(int(elapsed / 3600))
else:
return '{} days ago'.format((elapsed / 86400))
My current example:
Given datetime is 2017-07-27 01:18:58.398231
Current datetime is 2017-07-31 20:23:36.095440
Result is 19 hours (68677 seconds)
The following line returns only the 'seconds' component of the difference and does not take into account the days/hours/minutes components of it.
elapsed = (now - date).seconds
What you need is to use total_seconds() instead of just seconds since that's what you're trying to compare in subsequent conditions. Use it as follows:
elapsed = (now - date).total_seconds()
The rest of the code remains the same and you will get your desired output.
If you subtract two datetime objects the result will be a timedelta
import datetime as dt
import time
t1 = dt.datetime.now()
time.sleep(4)
t2 = dt.datetime.now()
dt1 = t2 - t1
print(dt1)
print(dt1.total_seconds())
print(type(dt1))
dt2 = t1 - t2
print(dt2.total_seconds())
print(dt2)
print(type(dt2))
If the second timestep was earlier than the first one, the results can be irritating. See negative day in example.
dt.seconds is only a part of the result, you are looking for
timedelta.total_seconds()
I want to calculate difference between two time in hours using django in sql db the time are stored in timefield.
I tried this:
def DesigInfo(request): # attendance summary
emplist = models.staff.objects.values('empId', 'name')
fDate = request.POST.get('fromDate')
tDate = request.POST.get('toDate')
if request.GET.get('empId_id'):
sel = attendance.objects.filter(empId_id=request.GET.get('empId_id'),)
for i in sel:
# print i.
# print i.outTime
# print i.inTime.hour,i.inTime.minute,i.inTime.second - i.outTime.hour,i.outTime.minute,i.outTime.second
ss = i.inTime.hour
ss1 = 12 - ss
mm = i.outTime.hour
mm1 = (12 + mm) - 12
print ss1 + mm1
Since i.inTime and i.outTime are time objects you cannot simply subtract them. A good approach is to convert them to datetime adding the date part (use today() but it is irrelevant to the difference), then subtract obtaining a timedelta object.
delta = datetime.combine(date.today(), i.outTime) - datetime.combine(date.today(), i.inTime)
(Look here: subtract two times in python)
Then if you want to express delta in hours:
delta_hours = delta.days * 24 + delta.seconds / 3600.0
A timedelta object has 3 properties representing 3 different resolutions for time differences (days, seconds and microseconds). In the last expression I avoided to add the microseconds but I suppose it is not relevant in your case. If it is also add delta.microseconds / 3600000000.0
Note that simply dividing seconds by 3600 would have returned only the integer part of hours avoiding fractions. It depends on your business rules how to round it up (round, floor, ceil or leave the fractional part as I did)
Using datetime objects: https://docs.python.org/2/library/datetime.html
A good stack overflow post on the topic How to get current time in Python
from datetime import datetime
now = datetime.now()
# wait some time
then = ... some time
# diff is a datetime.timedelta instance
diff = then - now
diff_hours = diff.seconds / 3600
You might want to play with this codes:
from datetime import datetime
#set the date and time format
date_format = "%m-%d-%Y %H:%M:%S"
#convert string to actual date and time
time1 = datetime.strptime('8-01-2008 00:00:00', date_format)
time2 = datetime.strptime('8-02-2008 01:30:00', date_format)
#find the difference between two dates
diff = time2 - time1
''' days and overall hours between two dates '''
print ('Days & Overall hours from the above two dates')
#print days
days = diff.days
print (str(days) + ' day(s)')
#print overall hours
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = days_to_hours + diff_btw_two_times
print (str(overall_hours) + ' hours');
''' now print only the time difference '''
''' between two times (date is ignored) '''
print ('\nTime difference between two times (date is not considered)')
#like days there is no hours in python
#but it has seconds, finding hours from seconds is easy
#just divide it by 3600
hours = (diff.seconds) / 3600
print (str(hours) + ' Hours')
#same for minutes just divide the seconds by 60
minutes = (diff.seconds) / 60
print (str(minutes) + ' Minutes')
#to print seconds, you know already ;)
print (str(diff.seconds) + ' secs')
The easiest way through I achieve is the comment of Zac given above. I was using relativedelta like this
from dateutil import relativedelta
difference = relativedelta.relativedelta( date1, date2)
no_of_hours = difference.hours
but it did not give me correct result when the days changes. So, I used the approach expressed above:
no_of_hours = (difference.days * 24) + (difference.seconds / 3600)
Please note that you will be getting negative value if date2 is greater than date1. So, you need to swipe the position of date variables in relativedelta.
I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I don't care what the full date is; just the hour. When I created datetime objects using strptime to specify a time, it threw in a dummy date (I think the year 1900?) which is not what I want. I could use a clumsy boolean expression like (hour == 8 and minute >= 30) or (9 <= hour < 15) but that doesn't seem very elegant. What's the easiest and most pythonic way to accomplish this?
Extending a bit further, what I'd really like is something that will tell me if it's between that range of hours, and that it's a weekday. Of course I can just use 0 <= weekday() <= 4 to hack this, but there might be a better way.
datetime objects have a method called time() which returns a time object (with no date information). You can then compare the time objects using the normal < or > operators.
import datetime
import time
timestamp = datetime.datetime.now().time() # Throw away the date information
time.sleep(1)
print (datetime.datetime.now().time() > timestamp) # >>> True (unless you ran this one second before midnight!)
# Or check if a time is between two other times
start = datetime.time(8, 30)
end = datetime.time(15)
print (start <= timestamp <= end) # >>> depends on what time it is
If you also want to check for weekdays, the code you suggest is probably the most effective way to go about it, but in that case you probably don't want to throw out the original datetime object.
now = datetime.datetime.now()
if 0 <= now.weekday() <= 4:
print ("It's a weekday!")
print (start <= now.time() <= end) # with start & end defined as above
from datetime import datetime, time
now = datetime.now()
if 0 <= now.weekday() <= 4:
print "it's a weekday"
if time(8, 30) <= now.time() <= time(15):
print "and it's in range"
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 9, 19, 3, 39, 38, 459765)
>>> 0 <= now.weekday() <= 4
True
>>> datetime.time(hour=8, minute=30) <= now.time() <= datetime.time(hour=15)
False
I don't know how you are getting your start and end time, but if you are limiting it to a single day, then be sure that the start time comes before the end time. If you had, for example, start time = 1800 and end time = 1200, you won't find any time in between on that day.
I want to write a simple python script which will check to see if it's 2 minutes before a given hour/minute, and then call my function either everyday or for a given date at the given time.
The script will run every minute in a cronjob.
So the two cases to execute myfunction():
10:55 everyday
10:55 on 9/28/2012
But I am having trouble determining when it's 2 minutes prior to the given hour/minute using datetime. Also, how to determine everyday vs just on a given day?
mydate = datetime(2012, 09,28, 10,55)
check = mydate - datetime.now() # gives you a timedelta
if check < datetime.timedelta(minutes=2):
run_myfunction()
The above sees if it's within 2 minutes, and if it is, then runs the myfunction(). The problem with the above code is that if the mydate has passed, the myfunction() will still run. Also, this requires that a specific date to be specified. How would one allow the check for everyday rather than 9/28/2012?
now = datetime.now()
mystart = now.replace(hour=10, minute=55, second=0)
myend = mystart + timedelta(minutes=2)
if mystart <= mydate < myend:
# do your stuff
Change your code like this
mydate = datetime(2012, 09,2, 10,55)
current_date = datetime.now()
check = mydate - current_date # gives you a timedelta
if mydate > current_date and check < datetime.timedelta(minutes=2):
run_myfunction()
It may be hackish, but you can use .total_seconds() to construct a range:
from datetime import datetime, timedelta
then = datetime(2012, 9, 18, 16, 5)
now = datetime.now()
delta = timedelta(minutes=10)
if 0 < (then - now).total_seconds() < delta.total_seconds():
# ...
That way, if then - now is a negative timedelta, total_seconds() will return a negative number and make your condition False.
For the everyday part, you can use
reference = datetime.datetime(2012,9,18,23,55,00)
now = datetime.datetime.now()
today = reference.replace(year=now.year,month=now.month,day=now.day)
For the time difference:
delta = (now-today)
lapse = delta.days * 86400 + delta.seconds
if abs(lapse) <= 2*60:
run_function()
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:
if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes
This generates a type error.
What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison.
Please post lists of datetime best practices.
Use the datetime.timedelta class:
>>> from datetime import datetime, timedelta
>>> then = datetime.now() - timedelta(hours = 2)
>>> now = datetime.now()
>>> (now - then) > timedelta(days = 1)
False
>>> (now - then) > timedelta(hours = 1)
True
Your example could be written as:
if (datetime.now() - self.timestamp) > timedelta(seconds = 100)
or
if (datetime.now() - self.timestamp) > timedelta(minutes = 100)
Compare the difference to a timedelta that you create:
if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):
print 'older'
Alternative:
if (datetime.now() - self.timestamp).total_seconds() > 100:
Assuming self.timestamp is an datetime instance
You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:
def seconds_difference(stamp1, stamp2):
delta = stamp1 - stamp2
return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.
Use abs() in the answer if you always want a positive number of seconds.
To discover how many seconds into the past a timestamp is, you can use it like this:
if seconds_difference(datetime.datetime.now(), timestamp) < 100:
pass
You can subtract two datetime objects to find the difference between them.
You can use datetime.fromtimestamp to parse a POSIX time stamp.
Like so:
# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
print "object is over 100 seconds old"
Convert your time delta into seconds and then use conversion back to hours elapsed and remaining minutes.
start_time=datetime(
year=2021,
month=5,
day=27,
hour=10,
minute=24,
microsecond=0)
end_time=datetime.now()
delta=(end_time-start_time)
seconds_in_day = 24 * 60 * 60
seconds_in_hour= 1 * 60 * 60
elapsed_seconds=delta.days * seconds_in_day + delta.seconds
hours= int(elapsed_seconds/seconds_in_hour)
minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)
print("Hours {} Minutes {}".format(hours,minutes))