Python Date Comparisons - python

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))

Related

add 2 hours in current time in Python and print the time in timestamp

How to get the current time and return that in timestamp format after adding 2 hours in it like 1535020200000
i tried the following but I am not getting the expected result
current_time + timedelta(hours=2)
(datetime.now()).split('.')[0] + timedelta(hours=2)
since the second one returns a string, addition operation cannot be done
I would recommend the following
from datetime import datetime, timedelta
two_hours_from_now = datetime.now() + timedelta(hours=2)
print(two_hours_from_now.timestamp())
You can do as follow:
import datetime
current_time = datetime.datetime.now()
later = current_time + datetime.timedelta(hours=2)
print(later.timestamp())
You get:
1535031690.031316
Quoting the documentation:
Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time().
If you need a timestamp, use time.time:
current_plus_2_hours = time.time() + 2 * 60 * 60
thanks to all of you, though this worked for me
start_at = 2
hours_from_now = int(str(time.time() + start_at * 60 * 60)[0:10]) * 1000

Why datetime substraction in Python doesn't subtract days?

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()

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.
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

What is the best way to check if time is within a certain minute?

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()

How to calculate the time interval between two time strings

I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved.
Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences.
For the averaging, should I convert to seconds and then average?
Yes, definitely datetime is what you need here. Specifically, the datetime.strptime() method, which parses a string into a datetime object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)
(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.
Try this -- it's efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting.
import time
start = time.time()
time.sleep(10) # or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
The time difference is returned as the number of elapsed seconds.
Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration):
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
Output
0:42:23
0:30:00
time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.:
#!/usr/bin/env python
from datetime import timedelta
def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)
data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.
This site says to try:
import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds/60
This forum uses time.mktime()
Structure that represent time difference in Python is called timedelta. If you have start_time and end_time as datetime types you can calculate the difference using - operator like:
diff = end_time - start_time
you should do this before converting to particualr string format (eg. before start_time.strftime(...)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.
I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps.
Not sure if it has some cons.
But looks neat for me :)
from datetime import datetime
from dateutil.relativedelta import relativedelta
t_a = datetime.now()
t_b = datetime.now()
def diff(t_a, t_b):
t_diff = relativedelta(t_b, t_a) # later/end time comes first!
return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)
Regarding to the question you still need to use datetime.strptime() as others said earlier.
Try this
import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time
OUTPUT :
0:00:05
import datetime as dt
from dateutil.relativedelta import relativedelta
start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
timedelta_obj.years,
timedelta_obj.months,
timedelta_obj.days,
timedelta_obj.hours,
timedelta_obj.minutes,
timedelta_obj.seconds,
)
result:
0 0 0 0 -47 -37
Both time and datetime have a date component.
Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime for each with the day set to today and subtract the start from the stop time to get the interval (timedelta).
Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.
you can use pendulum:
import pendulum
t1 = pendulum.parse("10:33:26")
t2 = pendulum.parse("10:43:36")
period = t2 - t1
print(period.seconds)
would output:
610
import datetime
day = int(input("day[1,2,3,..31]: "))
month = int(input("Month[1,2,3,...12]: "))
year = int(input("year[0~2020]: "))
start_date = datetime.date(year, month, day)
day = int(input("day[1,2,3,..31]: "))
month = int(input("Month[1,2,3,...12]: "))
year = int(input("year[0~2020]: "))
end_date = datetime.date(year, month, day)
time_difference = end_date - start_date
age = time_difference.days
print("Total days: " + str(age))
Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :
import datetime
def elapsed_interval(start,end):
elapsed = end - start
min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
hour, minutes = divmod(min, 60)
return '%.2d:%.2d:%.2d' % (hour,minutes,secs)
if __name__ == '__main__':
time_start=datetime.datetime.now()
""" do your process """
time_end=datetime.datetime.now()
total_time=elapsed_interval(time_start,time_end)
Usually, you have more than one case to deal with and perhaps have it in a pd.DataFrame(data) format. Then:
import pandas as pd
df['duration'] = pd.to_datetime(df['stop time']) - pd.to_datetime(df['start time'])
gives you the time difference without any manual conversion.
Taken from Convert DataFrame column type from string to datetime.
If you are lazy and do not mind the overhead of pandas, then you could do this even for just one entry.
Here is the code if the string contains days also [-1 day 32:43:02]:
print(
(int(time.replace('-', '').split(' ')[0]) * 24) * 60
+ (int(time.split(' ')[-1].split(':')[0]) * 60)
+ int(time.split(' ')[-1].split(':')[1])
)

Categories