Measuring Elapsed time using Python 2.7 time module - python

I am trying to find the difference between two times using time module and then convert it to datetime format using strftime but I get a strange output for elapsed time starting from 1970, what is the best way to find elapsed time using python?
start_time = time()
info('My Start Time ' + datetime.fromtimestamp(start_time).strftime('%d-%m-%Y %H:%M:%S'))
sleep(5)
elapsed_time = time() - start_time
info('My Elapsed Time' + datetime.fromtimestamp(elapsed_time).strftime('%d-%m-%Y %H:%M:%S'))
Output is
[2016-03-17 00:45:16.828277] INFO: Generic: My Start Time 17-03-2016 11:45:16
[2016-03-17 00:45:21.832503] INFO: Generic: My Elapsed Time 01-01-1970 10:00:05

Time intervals are different to times. It doesn't really make sense to convert a time interval like elapsed_time to a datetime.
Your script can be simplified considerably by using the datetime module's datetime and timedelta objects. When you subtract one datetime from another the result is a timedelta.
from time import sleep
from datetime import datetime
start_time = datetime.now()
print('My Start Time', start_time)
sleep(5)
stop_time = datetime.now()
print('My Stop Time', stop_time)
elapsed_time = stop_time - start_time
print('My Elapsed Time', elapsed_time)
output
My Start Time 2016-03-17 12:28:01.262090
My Stop Time 2016-03-17 12:28:06.265964
My Elapsed Time 0:00:05.003874
Please see the docs for timedelta to see more examples of what you can do with these objects.

This is one of my favourite things! Your problem is that, as far as the time module is concerned... time began on January 1st 1970!! See the docs here.
Time starts counting from this date so what you are basically saying when you convert your elapsed time to a date, is give me 01/01/1970 + my elapsed time.
Besides I'm not sure if taking the elapsed time as a date is really what you want. Don't you want to measure this in hours, minutes, etc. ? If you really do want the date, you should just call new_time = time.time() and then convert new_time to the format you want (without bothering to calculate elapsed time as a date)

Instead of making your final timestamp from "elapsed time", you might want to do "start time" + "elapsed time" :)
start_time = time()
info('My Start Time ' + datetime.fromtimestamp(start_time).strftime('%d-%m-%Y %H:%M:%S'))
sleep(5)
elapsed_time = time() - start_time
info('My Elapsed Time' + datetime.fromtimestamp(elapsed_time + start_time).strftime('%d-%m-%Y %H:%M:%S'))
This is because Python's Time module's epoch is January 1, 1970. Calling time() measures the seconds since the epoch (.strftime('%d-%m-%Y %H:%M:%S') just reformats the seconds to a date we can understand)
So when you find elapsed_time, you end up with seconds between when you first started and the time you assigned the variable. Thus, it makes sense for datetime.fromtimestamp(elapsed_time) to output Jan 1, 1970 10:00:05. Where elapsed_time is 5, start_time is 1458177108.6...You want the result to be start_time PLUS elapsed_time (or, simply, why not just the current time?)
I hope this explanation made sense. Here's more explanation from the Python docs https://docs.python.org/2/library/time.html

Related

How to define a difference in time in seconds between a timestamp saved as a string and a current UTC timestamp

I am testing the difference between an actual UTC time and timestamp when my object was saved in a table (UTC). It must be not more than 60 seconds.
Example of timestamp_from_table (string from my site): 2021-02-05 13:51:52
After researching for options to make this, I came to this approach:
timestamp_from_table = driver.find_element_by_css_selector("my_locator").text
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()) # current time converted to string
current_time_truncated = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S") # cutting milliseconds
date_time_obj = datetime.strptime(timestamp_from_table, '%Y-%m-%d %H:%M:%S') # converting string timestamp to a datetime object
time_difference = current_time_truncated - date_time_obj
result = time_difference.seconds # datetime.timedelta represented in seconds
assert result in range(1, 60), error()
It works just fine, but probably there is a shorter way to compare a difference between a timestamp saved as string and actual utc timestamp. Thanks for any advice.
I'm reading between the lines a bit, but it sounds like at a high level your goal is to calculate the elapsed seconds between two times. If I'm right about that, here is a typical way to do it in Python:
import datetime
import time
previous = datetime.datetime.now()
time.sleep(5) # Added to simulate the passing of time for demonstration purposes
current = datetime.datetime.now()
elapsed_seconds = (current - previous) / datetime.timedelta(seconds=1)
"Division" by timedelta is the key to getting elapsed seconds (or any other time unit) between two datetime objects. While not UTC specific hopefully this shines a light on an approach that works for you.

Python taking away time

I am trying to take away one time to the other to find out how long the users account will be locked for but instead of getting this:
0:23:48:55
I get this:
21 days , 23:48:55
I am using this method:
end_time = accounts[user].get("today")
start_time = datetime.datetime.now().time().strftime("%d:%H:%M:%S")
total_time =(datetime.datetime.strptime(end_time,'%d:%H:%M:%S') - datetime.datetime.strptime(start_time, '%d:%H:%M:%S'))
print(total_time)
The end_time has tomorrows date in it which is:
23:14:29:21
so taking the current time away should give:
0:23:48:21
but not 21 days.
Any ideas why this is doing that and how to fix this
The problem comes from your start_time because .time() remove the value of the day.
end_time = "23:14:29:21"
start_time = datetime.datetime.now().strftime("%d:%H:%M:%S")
total_time =(datetime.datetime.strptime(end_time,'%d:%H:%M:%S') - datetime.datetime.strptime(start_time, '%d:%H:%M:%S'))
print(total_time)
Would Be More Like This, The .time() Function Removes The Value Of The Day (Instead Of Counting The Number Of Days (Like 0,1))
#Fixed Code
end_time = "23:14:29:21"
start_time = time.strftime("%d:%H:%M:%S")
total_time =(datetime.datetime.strptime(end_time,'%d:%H:%M:%S') - datetime.datetime.strptime(start_time, '%d:%H:%M:%S'))
print(total_time)
changed
start_time = datetime.datetime.now().time().strftime("%d:%H:%M:%S")
to
start_time = time.strftime("%d:%H:%M:%S")

Python Elapsed Time as Days, Hours, Minutes, Seconds

I would like to measure the execution time of some piece of code in days, hours, minutes and seconds.
This is what I have so far:
import time
start_time = time.time()
# some code
elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time))
print(f"Took: {elapsed}")
The problem is that if the code that I am measuring takes longer than 24h, the time displayed overflows and starts from zero again. I would like something like this:
# Example: 12 hours and 34 minutes should be printed as
> Took: 12:34:00
# Example: 26 hours and 3 minutes should be printed as
> Took: 1:02:03:00
You could use datetime:
from datetime import datetime as dt
start = dt.fromtimestamp(1588432670)
end = dt.now()
elapsed=end-start
print("Took: %02d:%02d:%02d:%02d" % (elapsed.days, elapsed.seconds // 3600, elapsed.seconds // 60 % 60, elapsed.seconds % 60))
Output:
Took: 33:00:21:49
The result of time.gmtime(time.time() - start_time) is not what you seem to think it is. Instead of being a duration of time it is a point in time. Let me explain.
The result of time.time() is the number of seconds since January 1, 1970, 00:00:00 (UTC) at the time of calling. Therefore, the statement time.time() - start_time will produce the number of seconds between the two calls. So far so good. However, the time.gmtime function is interpreting this duration as the number of seconds since January 1, 1970, 00:00:00 (UTC) and formatting the time accordingly. What you are seeing then is the time portion of the date January 1, 1970, 12:34:00 (UTC).
I suggest you either use the datetime.timedelta object and format using that, or as others have suggested, output the duration in seconds or milliseconds.
If you want to format this number yourself, you could use something like this:
def format_duration(duration):
mapping = [
('s', 60),
('m', 60),
('h', 24),
]
duration = int(duration)
result = []
for symbol, max_amount in mapping:
amount = duration % max_amount
result.append(f'{amount}{symbol}')
duration //= max_amount
if duration == 0:
break
if duration:
result.append(f'{duration}d')
return ' '.join(reversed(result))
You should try this:
import time
start_time = time.time()
...
elapsed_time = time.time() - start_time
days = 0
if elapsed_time >= 86400:
days = int(elapsed_time / 86400)
elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time))
if days == 0:
print(f"Took: {elapsed}")
else:
print(f"Took: {days}:{eplased}")
Time types can only include hours and less units. You should use datetime instead of time as follows:
from datetime import datetime
start_time = datetime.now()
# some code
elapsed = datetime.now() - start_time)
print(f"Took: {elapsed}")
Example usage of Datetime:
from datetime import datetime
d1 = datetime(2013,9,1,5,5,4)
d2 = datetime(2013,1,13,3,2,1)
result1 = d1-d2
print ('{} between {} and {}'.format(result1, d1, d2))
This produces following output:
231 days, 2:03:03 between 2013-09-01 05:05:04 and 2013-01-13 03:02:01
Try using timeit:
import timeit
timeit.timeit(<callable function>, number = 100)
Here timeit will call callable function number times and give you the average runtime.

How can I print elapsed time in ms using python

I am able to compute elapsed time, but I dont know how to print results in ms (i need integer, like this: 20ms, 30ms..)
import datetime
start_time = datetime.datetime.now()
print 'some long procedure'
elapsed = datetime.datetime.now() - start_time
print int(elapsed).strftime("%s")) * 1000 #<------- not working
The total_seconds method of datetime.timedelta objects returns the number of seconds, as a float, so it includes the fractions of second - see timedelta.total_seconds.
So, you just have to multiply it by 1000 to convert it to milliseconds, and keep the integer part.
import datetime
start_time = datetime.datetime.now()
print 'some long procedure'
elapsed = datetime.datetime.now() - start_time
print(int(elapsed.total_seconds()*1000))

Python, datetime "time gap" percentage

Assume I have these datatime variables:
start_time, end_time, current_time
I would like to know how much time left as percentage by checking current_time and the time delta between start_time and the end_time
IE: Assume the interval is a 24 hours betwen start_time and end_time yet between current_time and end_time, there are 6 hours left to finish, %25 should be left.
How can this be done ?
In Python 2.7.x, time delta has a method total_seconds to achieve this:
import datetime
startTime = datetime.datetime.now() - datetime.timedelta(hours=2)
endTime = datetime.datetime.now() + datetime.timedelta(hours=4)
rest = endTime - datetime.datetime.now()
total = endTime - startTime
print "left: {:.2%}".format(rest.total_seconds()/total.total_seconds())
In Python 3.2, you can apparently divide the time deltas directly (without going through total_seconds).
(This has also been noted in Python 2.6.5: Divide timedelta with timedelta.)
Here's a hackish workaround: compute the total number of microseconds between the two values by using the days, seconds, and microseconds fields. Then divide by the total number of microseconds in the interval.
Possibly simplest:
import time
def t(dt):
return time.mktime(dt.timetuple())
def percent(start_time, end_time, current_time):
total = t(end_time) - t(start_time)
current = t(current_time) - t(start_time)
return (100.0 * current) / total

Categories