import datetime
start_time = datetime.datetime.now()
end_time = datetime.datetime.now()
print (end_time - start_time)
I try to to use datetime to get the execution time.
If it took almost 11 hours, it will show like 11:07:13.215032
If more than 24 hours, how to show the time?
e.g. 35 hours 11minutes 37 seconds
1) 35:11:37
2) 1:11:11:37
Which one will be shown?
Just give it a start_time
import datetime
start_time = datetime.datetime.strptime('1997-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')
end_time = datetime.datetime.now()
print (end_time - start_time)
Output:
7363 days, 17:06:57.965556
Related
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.
I'm trying to find the difference between the StartTime and LastTime (minutes) in this DataFrame:
StartTime LastTime
1 00:02:05 00:02:05
2 00:07:05 00:07:05
3 00:12:06 00:12:06
4 00:17:06 00:17:06
When I run the following code on the data
from datetime import datetime
date_format = "%H:%M.%S"
# You could also pass datetime.time object in this part and convert it to string.
time_start = str(UDP_interval['StartTime'])
time_end = str(UDP_interval['LastTime'])
# Then get the difference here.
diff = datetime.strptime(time_end, date_format) -
datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
I get this error:
dtype: object' does not match format '%H:%M:%S'
You should probably just use:
t_start = list(map(int, str(UDP_interval['StartTime']).split(':'))) # get hours, minutes, seconds separately
t_end = list(map(int, str(UDP_interval['LastTime']).split(':')))
diff = (t_start[0] - t_end[0]) + (t_start[1] - t_start[1]) / 60 + (t_start[2] - t_start[2]) / 3600
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
I am hoping to generate a range of timestamps between:
18:00 (EST) on October 6th, 2014
and the same time 400 seconds later with an interval size of 2.2 seconds.
Getting the start and end dates:
When I do the following:
start_time = datetime.datetime(year = 2014,
month = 10,
day = 6,
hour = 18,
tzinfo = pytz.timezone('US/Eastern'))
end_time = start_time + datetime.timedelta(seconds=400)
Something seems to fail:
start_time.isoformat() returns '2014-10-06T18:06:40-04:56'
end_time.isoformat() returns '2014-10-06T18:06:40-04:56'
note that the time-zone offset for both timestamps above are: -04:56 (4 hours and 56 minutes) even though EST is 5 hours behind UTC. ?
Getting the time range:
Moving forward, if I try to get a range of timestamps between these two dates every 2.2 seconds (i.e. 2200 ms):
ts = pd.date_range(start=start_time, end=end_time, freq='2200L')
I get:
> ts[0]
Timestamp('2014-10-06 18:56:00-0400', tz='US/Eastern', offset='2200L')
or in other words:
> ts[0].isoformat()
'2014-10-06T18:56:00-04:00'
which also does not make sense (note that the time is 18:56, even though I was asking to get a range between 18:00 and 18:06:40 (i.e. 400 seconds after 18:00)
I got tired of dealing with Python's awkward datetime implementation (particularly with respect to timezones), and have started using crsmithdev.com/arrow. A solution using this lib:
import arrow
start_time = arrow.get(2014, 10, 6, tzinfo='US/Eastern')
end_time = start_time.replace(seconds=400)
print start_time.isoformat()
print end_time.isoformat()
# alternate form
start_time = arrow.get('2014-10-06T18:00:00.000-04:00')
end_time = start_time.replace(seconds=400)
print start_time.isoformat()
print end_time.isoformat()
# get a datetime from an arrow object
start_time_dt = start_time.datetime
import dateutil.parser as parser
import datetime
start_time = parser.parse("06/Oct/2015 18:00 EST")
end_time = start_time + datetime.timedelta(seconds=400)
interval = datetime.timedelta(seconds=2.2)
current_time = start_time
while current_time < end_time:
current_time += interval
print current_time
but I probably dont understand what your issue is
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