Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn’t be surprised.)
>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]
回答 8
您可以使用gmtime
from time import gmtime
detailed_time = gmtime()#returns a struct_time object for current time
year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min
from time import gmtime
detailed_time = gmtime()
#returns a struct_time object for current time
year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min
Note: A time stamp can be passed to gmtime, default is current time as
returned by time()
timetuple() can be zipped with another array, which creates labeled tuples. Cast that to a dictionary and the resultant product can be consumed with get_current_datetime_as_dict()['year'].
This has a little more overhead than some of the other solutions on here, but I’ve found it’s so nice to be able to access named values for clartiy’s sake in the code.
import time
from threading importThreadclass worker(Thread):def run(self):for x in xrange(0,11):print x
time.sleep(1)class waiter(Thread):def run(self):for x in xrange(100,103):print x
time.sleep(5)def run():
worker().start()
waiter().start()
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you’ll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
It will just sleep the thread except in the case where your application has only a single thread, in which case it will sleep the thread and effectively the process as well.
The python documentation on sleep doesn’t specify this however, so I can certainly understand the confusion!
The thread will block, but the process is still alive.
In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly ‘sleep’ will block and the other threads still run within the process.
Process is not runnable by itself. In regard to execution, process is just a container for threads. Meaning you can’t pause the process at all. It is simply not applicable to process.
Given a datetime.time value in Python, is there a standard way to add an integer number of seconds to it, so that 11:34:59 + 3 = 11:35:02, for example?
These obvious ideas don’t work:
>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3)# days, seconds, then other fields.print(a.time())print(b.time())
You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value.
For example:
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
results in the two values, three seconds apart:
11:34:59
11:35:02
You could also opt for the more readable
b = a + datetime.timedelta(seconds=3)
if you’re so inclined.
If you’re after a function that can do this, you can look into using addSecs below:
from datetime import datetime, date, time, timedelta
sometime = time(8,00)# 8am
later =(datetime.combine(date.today(), sometime)+ timedelta(seconds=3)).time()
As others here have stated, you can just use full datetime objects throughout:
from datetime import datetime, date, time, timedelta
sometime = time(8,00) # 8am
later = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()
However, I think it’s worth explaining why full datetime objects are required. Consider what would happen if I added 2 hours to 11pm. What’s the correct behavior? An exception, because you can’t have a time larger than 11:59pm? Should it wrap back around?
Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you’re not allowed to add timedelta objects to time objects.
回答 2
一件事,可能会增加清晰度以覆盖默认值(秒)
>>> b = a + datetime.timedelta(seconds=3000)>>> b
datetime.datetime(1,1,1,12,24,59)
Thanks to @Pax Diablo, @bvmou and @Arachnid for the suggestion of using full datetimes throughout. If I have to accept datetime.time objects from an external source, then this seems to be an alternative add_secs_to_time() function:
If it’s worth adding another file / dependency to your project, I’ve just written a tiny little class that extends datetime.time with the ability to do arithmetic. When you go past midnight, it wraps around zero. Now, “What time will it be, 24 hours from now” has a lot of corner cases, including daylight savings time, leap seconds, historical timezone changes, and so on. But sometimes you really do need the simple case, and that’s what this will do.
You cannot simply add number to datetime because it’s unclear what unit is used: seconds, hours, weeks…
There is timedelta class for manipulations with date and time. datetime minus datetime gives timedelta, datetime plus timedelta gives datetime, two datetime objects cannot be added although two timedelta can.
Create timedelta object with how many seconds you want to add and add it to datetime object:
Try adding a datetime.datetime to a datetime.timedelta. If you only want the time portion, you can call the time() method on the resultant datetime.datetime object to get it.
def add_timedelta_to_time(t, td):"""Add a timedelta object to a time object using a dummy datetime.
:param t: datetime.time object.
:param td: datetime.timedelta object.
:returns: datetime.time object, representing the result of t + td.
NOTE: Using a gigantic td may result in an overflow. You've been
warned.
"""# Create a dummy date object.
dummy_date = date(year=100, month=1, day=1)# Combine the dummy date with the given time.
dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)# Add the timedelta to the dummy datetime.
new_datetime = dummy_datetime + td
# Return the resulting time, including timezone information.return new_datetime.timetz()
Old question, but I figured I’d throw in a function that handles timezones. The key parts are passing the datetime.time object’s tzinfo attribute into combine, and then using timetz() instead of time() on the resulting dummy datetime. This answer partly inspired by the other answers here.
def add_timedelta_to_time(t, td):
"""Add a timedelta object to a time object using a dummy datetime.
:param t: datetime.time object.
:param td: datetime.timedelta object.
:returns: datetime.time object, representing the result of t + td.
NOTE: Using a gigantic td may result in an overflow. You've been
warned.
"""
# Create a dummy date object.
dummy_date = date(year=100, month=1, day=1)
# Combine the dummy date with the given time.
dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)
# Add the timedelta to the dummy datetime.
new_datetime = dummy_datetime + td
# Return the resulting time, including timezone information.
return new_datetime.timetz()
And here’s a really simple test case class (using built-in unittest):
import unittest
from datetime import datetime, timezone, timedelta, time
class AddTimedeltaToTimeTestCase(unittest.TestCase):
"""Test add_timedelta_to_time."""
def test_wraps(self):
t = time(hour=23, minute=59)
td = timedelta(minutes=2)
t_expected = time(hour=0, minute=1)
t_actual = add_timedelta_to_time(t=t, td=td)
self.assertEqual(t_expected, t_actual)
def test_tz(self):
t = time(hour=4, minute=16, tzinfo=timezone.utc)
td = timedelta(hours=10, minutes=4)
t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)
t_actual = add_timedelta_to_time(t=t, td=td)
self.assertEqual(t_expected, t_actual)
if __name__ == '__main__':
unittest.main()
>>>import timeit
>>> setup ='''
import random
random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''>>>print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7,1000))0.334147930145
The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn’t affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).
Here is an example of how to set up a test for sorting:
>>> import timeit
>>> setup = '''
import random
random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''
>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145
Note that the series of statements makes a fresh copy of the unsorted data on every pass.
Also, note the timing technique of running the measurement suite seven times and keeping only the best time — this can really help reduce measurement distortions due to other processes running on your system.
Those are my tips for using timeit correctly. Hope this helps :-)
>>>def f(x):...return x * x
...>>>import timeit
>>> timeit.repeat("for x in range(100): f(x)","from __main__ import f",
number=100000)[2.0640320777893066,2.0876040458679199,2.0520210266113281]
If you want to use timeit in an interactive Python session, there are two convenient options:
Use the IPython shell. It features the convenient %timeit special function:
In [1]: def f(x):
...: return x*x
...:
In [2]: %timeit for x in range(100): f(x)
100000 loops, best of 3: 20.3 us per loop
In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement:
>>> def f(x):
... return x * x
...
>>> import timeit
>>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f",
number=100000)
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
from functools import partial
def to_time(items):...
test_items =[1,2,3]*100
times = timeit.Timer(partial(to_time, test_items)).repeat(3,1000)# Divide by the number of repeats
time_taken = min(times)/1000
I’ll let you in on a secret: the best way to use timeit is on the command line.
On the command line, timeit does proper statistical analysis: it tells you how long the shortest run took. This is good because all error in timing is positive. So the shortest time has the least error in it. There’s no way to get negative error because a computer can’t ever compute faster than it can compute!
So, the command-line interface:
%~> python -m timeit "1 + 2"
10000000 loops, best of 3: 0.0468 usec per loop
That’s quite simple, eh?
You can set stuff up:
%~> python -m timeit -s "x = range(10000)" "sum(x)"
1000 loops, best of 3: 543 usec per loop
which is useful, too!
If you want multiple lines, you can either use the shell’s automatic continuation or use separate arguments:
%~> python -m timeit -s "x = range(10000)" -s "y = range(100)" "sum(x)" "min(y)"
1000 loops, best of 3: 554 usec per loop
That gives a setup of
x = range(1000)
y = range(100)
and times
sum(x)
min(y)
If you want to have longer scripts you might be tempted to move to timeit inside a Python script. I suggest avoiding that because the analysis and timing is simply better on the command line. Instead, I tend to make shell scripts:
which would give you something closer to the interface from the command-line, but in a much less cool manner. The "from __main__ import ..." lets you use code from your main module inside the artificial environment created by timeit.
It’s worth noting that this is a convenience wrapper for Timer(...).timeit(...) and so isn’t particularly good at timing. I personally far prefer using Timer(...).repeat(...) as I’ve shown above.
Warnings
There are a few caveats with timeit that hold everywhere.
Overhead is not accounted for. Say you want to time x += 1, to find out how long addition takes:
>>> python -m timeit -s "x = 0" "x += 1"
10000000 loops, best of 3: 0.0476 usec per loop
Well, it’s not 0.0476 µs. You only know that it’s less than that. All error is positive.
So try and find pure overhead:
>>> python -m timeit -s "x = 0" ""
100000000 loops, best of 3: 0.014 usec per loop
That’s a good 30% overhead just from timing! This can massively skew relative timings. But you only really cared about the adding timings; the look-up timings for x also need to be included in overhead:
>>> python -m timeit -s "x = 0" "x"
100000000 loops, best of 3: 0.0166 usec per loop
The difference isn’t much larger, but it’s there.
Mutating methods are dangerous.
>>> python -m timeit -s "x = [0]*100000" "while x: x.pop()"
10000000 loops, best of 3: 0.0436 usec per loop
But that’s completely wrong!x is the empty list after the first iteration. You’ll need to reinitialize:
>>> python -m timeit "x = [0]*100000" "while x: x.pop()"
100 loops, best of 3: 9.79 msec per loop
But then you have lots of overhead. Account for that separately.
>>> python -m timeit "x = [0]*100000"
1000 loops, best of 3: 261 usec per loop
Note that subtracting the overhead is reasonable here only because the overhead is a small-ish fraction of the time.
For your example, it’s worth noting that both Insertion Sort and Tim Sort have completely unusual timing behaviours for already-sorted lists. This means you will require a random.shuffle between sorts if you want to avoid wrecking your timings.
# Генерация целых чисел
def gen_prime(x):
multiples = []
results = []
for i in range(2, x+1):
if i not in multiples:
results.append(i)
for j in range(i*i, x+1, i):
multiples.append(j)
return results
import timeit
# Засекаем время
start_time = timeit.default_timer()
gen_prime(3000)
print(timeit.default_timer() - start_time)
# start_time = timeit.default_timer()
# gen_prime(1001)
# print(timeit.default_timer() - start_time)
import timeit
print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
lets setup the same dictionary in each of the following and test the execution time.
The setup argument is basically setting up the dictionary
Number is to run the code 1000000 times. Not the setup but the stmt
When you run this you can see that index is way faster than get. You can run it multiple times to see.
The code basically tries to get the value of c in the dictionary.
import timeit
print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
Here are my results, yours will differ.
by index: 0.20900007452246427
by get: 0.54841166886888
回答 9
只需将整个代码作为timeit的参数传递:
import timeit
print(timeit.timeit("""
limit = 10000
prime_list = [i for i in range(2, limit+1)]
for prime in prime_list:
for elem in range(prime*2, max(prime_list)+1, prime):
if elem in prime_list:
prime_list.remove(elem)
""", number=10))
simply pass your entire code as an argument of timeit:
import timeit
print(timeit.timeit(
"""
limit = 10000
prime_list = [i for i in range(2, limit+1)]
for prime in prime_list:
for elem in range(prime*2, max(prime_list)+1, prime):
if elem in prime_list:
prime_list.remove(elem)
"""
, number=10))
回答 10
import timeit
def oct(x):return x*x
timeit.Timer("for x in range(100): oct(x)","gc.enable()").timeit()
The built-in timeit module works best from the IPython command line.
To time functions from within a module:
from timeit import default_timer as timer
import sys
def timefunc(func, *args, **kwargs):
"""Time a function.
args:
iterations=3
Usage example:
timeit(myfunc, 1, b=2)
"""
try:
iterations = kwargs.pop('iterations')
except KeyError:
iterations = 3
elapsed = sys.maxsize
for _ in range(iterations):
start = timer()
result = func(*args, **kwargs)
elapsed = min(timer() - start, elapsed)
print(('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, elapsed)))
return result
回答 12
如何将Python REPL解释器与接受参数的函数一起使用的示例。
>>>import timeit
>>>def naive_func(x):... a =0...for i in range(a):... a += i
...return a
>>>def wrapper(func,*args,**kwargs):...def wrapper():...return func(*args,**kwargs)...return wrapper
>>> wrapped = wrapper(naive_func,1_000)>>> timeit.timeit(wrapped, number=1_000_000)0.4458435332577161
You would create two functions and then run something similar to this.
Notice, you want to choose the same number of execution/run to compare apple to apple.
This was tested under Python 3.7.
Here is the code for ease of copying it
!/usr/local/bin/python3
import timeit
def fibonacci(n):
"""
Returns the n-th Fibonacci number.
"""
if(n == 0):
result = 0
elif(n == 1):
result = 1
else:
result = fibonacci(n-1) + fibonacci(n-2)
return result
if __name__ == '__main__':
import timeit
t1 = timeit.Timer("fibonacci(13)", "from __main__ import fibonacci")
print("fibonacci ran:",t1.timeit(number=1000), "milliseconds")
import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
will print out, for 2 seconds:
'00:00:02'
and for 7 minutes one second:
'00:07:01'
note that the minimum time unit with gmtime is seconds. If you need microseconds consider the following:
import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds)
For the best measure of elapsed time (since Python 3.3), use time.perf_counter().
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
For measurements on the order of hours/days, you don’t care about sub-second resolution so use time.monotonic() instead.
Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
In many implementations, these may actually be the same thing.
On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.
Update for Python 3.7
New in Python 3.7 is PEP 564 — Add new time functions with nanosecond resolution.
Use of these can further eliminate rounding and floating-point errors, especially if you’re measuring very short periods, or your application (or Windows machine) is long-running.
Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.
Update for Python 3.8
time.clock is now gone.
回答 4
更长的时间。
import time
start_time = time.time()...
e = int(time.time()- start_time)print('{:02d}:{:02d}:{:02d}'.format(e //3600,(e %3600//60), e %60))
import time
start_time = time.time()
...
e = int(time.time() - start_time)
print('{:02d}:{:02d}:{:02d}'.format(e // 3600, (e % 3600 // 60), e % 60))
would print
00:03:15
if more than 24 hours
25:33:57
That is inspired by Rutger Hofste’s answer. Thank you Rutger!
回答 5
您需要导入时间,然后使用time.time()方法知道当前时间。
import time
start_time=time.time()#taking current time as starting time#here your code
elapsed_time=time.time()-start_time #again taking current time - starting time
You need to import time and then use time.time() method to know current time.
import time
start_time=time.time() #taking current time as starting time
#here your code
elapsed_time=time.time()-start_time #again taking current time - starting time
回答 6
安排时间的另一种不错的方法是使用with python结构。
具有结构的对象会自动调用__enter__和__exit__方法,这正是我们计时所需的时间。
让我们创建一个Timer类。
from time import time
classTimer():def __init__(self, message):
self.message = message
def __enter__(self):
self.start = time()returnNone# could return anything, to be used like this: with Timer("Message") as value:def __exit__(self, type, value, traceback):
elapsed_time =(time()- self.start)*1000print(self.message.format(elapsed_time))
然后,可以使用Timer类,如下所示:
withTimer("Elapsed time to compute some prime numbers: {}ms"):
primes =[]for x in range(2,500):ifnot any(x % p ==0for p in primes):
primes.append(x)print("Primes: {}".format(primes))
Another nice way to time things is to use the with python structure.
with structure is automatically calling __enter__ and __exit__ methods which is exactly what we need to time things.
Let’s create a Timer class.
from time import time
class Timer():
def __init__(self, message):
self.message = message
def __enter__(self):
self.start = time()
return None # could return anything, to be used like this: with Timer("Message") as value:
def __exit__(self, type, value, traceback):
elapsed_time = (time() - self.start) * 1000
print(self.message.format(elapsed_time))
Then, one can use the Timer class like this:
with Timer("Elapsed time to compute some prime numbers: {}ms"):
primes = []
for x in range(2, 500):
if not any(x % p == 0 for p in primes):
primes.append(x)
print("Primes: {}".format(primes))
Vadim Shender response is great. You can also use a simpler decorator like below:
import datetime
def calc_timing(original_function):
def new_function(*args,**kwargs):
start = datetime.datetime.now()
x = original_function(*args,**kwargs)
elapsed = datetime.datetime.now()
print("Elapsed Time = {0}".format(elapsed-start))
return x
return new_function()
@calc_timing
def a_func(*variables):
print("do something big!")
回答 8
在编程中,有两种主要的时间测量方法,结果不同:
>>>print(time.process_time()); time.sleep(10);print(time.process_time())0.117513940000000010.11764988400000001# took 0 seconds and a bit>>>print(time.perf_counter()); time.sleep(10);print(time.perf_counter())3972.4657703263982.468109075# took 10 seconds and a bit
In programming, there are 2 main ways to measure time, with different results:
>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001 # took 0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075 # took 10 seconds and a bit
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.
Use time.process_time()
Wall-Clock Time: This refers to how much time has passed “on a clock hanging on the wall”, i.e. outside real time.
Use time.perf_counter()
time.time() also measures wall-clock time but can be reset, so you could go back in time
time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
回答 9
这是Vadim Shender的巧妙代码的更新,带有表格输出:
import collections
import time
from functools import wraps
PROF_DATA = collections.defaultdict(list)def profile(fn):@wraps(fn)def with_profiling(*args,**kwargs):
start_time = time.time()
ret = fn(*args,**kwargs)
elapsed_time = time.time()- start_time
PROF_DATA[fn.__name__].append(elapsed_time)return ret
return with_profiling
Metrics= collections.namedtuple("Metrics","sum_time num_calls min_time max_time avg_time fname")def print_profile_data():
results =[]for fname, elapsed_times in PROF_DATA.items():
num_calls = len(elapsed_times)
min_time = min(elapsed_times)
max_time = max(elapsed_times)
sum_time = sum(elapsed_times)
avg_time = sum_time / num_calls
metrics =Metrics(sum_time, num_calls, min_time, max_time, avg_time, fname)
results.append(metrics)
total_time = sum([m.sum_time for m in results])print("\t".join(["Percent","Sum","Calls","Min","Max","Mean","Function"]))for m in sorted(results, reverse=True):print("%.1f\t%.3f\t%d\t%.3f\t%.3f\t%.3f\t%s"%(100* m.sum_time / total_time, m.sum_time, m.num_calls, m.min_time, m.max_time, m.avg_time, m.fname))print("%.3f Total Time"% total_time)
Python2.7.3(default,Apr242012,00:00:54)[GCC 4.7.020120414(prerelease)] on linux2
Type"help","copyright","credits"or"license"for more information.>>>import time
>>> ts = time.time()>>>print ts
1355563265.81>>>import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')>>>print st
2012-12-1501:21:05>>>
The time.time() function returns the number of seconds since the epoch, as seconds. Note that the “epoch” is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where you are “seconds past epoch” (time.time()) returns the same value at the same moment.
Here is some sample output I ran on my computer, converting it to a string as well.
Python 2.7.3 (default, Apr 24 2012, 00:00:54)
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> ts = time.time()
>>> print ts
1355563265.81
>>> import datetime
>>> st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2012-12-15 01:21:05
>>>
The ts variable is the time returned in seconds. I then converted it to a string using the datetime library making it a string that is human readable.
This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])
You can get the timestamp as a string using the .now() or .utcnow() of the datetime.datetime:
neither: time.time() returns approximately the number of seconds elapsed since the Epoch. The result doesn’t depend on timezone so it is neither UTC nor local time. Here’s POSIX defintion for “Seconds Since the Epoch”.
both: time.time() doesn’t require your system’s clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds):
from datetime import datetime
utc_dt = datetime.utcfromtimestamp(timestamp)
There is no such thing as an “epoch” in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.
timestamp is always time in utc, but when you call datetime.datetime.fromtimestamp it returns you time in your local timezone corresponding to this timestamp, so result depend of your locale.
another solution is the function you can embed into your own utils.py
import time as time_ #make sure we don't override time
def millis():
return int(round(time_.time() * 1000))
回答 6
如果您想在代码中使用一个简单的方法来返回带有datetime的毫秒数:
from datetime import datetime
from datetime import timedelta
start_time = datetime.now()# returns the elapsed milliseconds since the start of the programdef millis():
dt = datetime.now()- start_time
ms =(dt.days *24*60*60+ dt.seconds)*1000+ dt.microseconds /1000.0return ms
If you want a simple method in your code that returns the milliseconds with datetime:
from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
# returns the elapsed milliseconds since the start of the program
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms
If you’re concerned about measuring elapsed time, you should use the monotonic clock (python 3). This clock is not affected by system clock updates like you would see if an NTP query adjusted your system time, for example.
>>> import time
>>> millis = round(time.monotonic() * 1000)
It provides a reference time in seconds that can be used to compare later to measure elapsed time.
If you use my code (below), the time will appear in seconds, then, after a decimal, milliseconds. I think that there is a difference between Windows and Unix – please comment if there is.
These multiplications to 1000 for milliseconds may be decent for solving or making some prerequisite acceptable. It could be used to fill a gap in your database which doesn’t really ever use it. Although, for real situations which require precise timing it would ultimately fail. I wouldn’t suggest anyone use this method for mission-critical operations which require actions, or processing at specific timings.
For example:
round-trip pings being 30-80ms in the USA… You couldn’t just round that up and use it efficiently.
My own example requires tasks at every second which means if I rounded up after the first tasks responded I would still incur the processing time multiplied every main loop cycle. This ended up being a total function call every 60 seconds. that’s ~1440 a day.. not too accurate.
Just a thought for people looking for more accurate reasoning beyond solving a database gap which never really uses it.
On Unix, return the current processor time as a floating point number
expressed in seconds. The precision, and in fact the very definition
of the meaning of “processor time”, depends on that of the C function
of the same name, but in any case, this is the function to use for
benchmarking Python or timing algorithms.
On Windows, this function returns wall-clock seconds elapsed since the
first call to this function, as a floating point number, based on the
Win32 function QueryPerformanceCounter(). The resolution is typically
better than one microsecond.
Additionally, there is the timeit module for benchmarking code snippets.
The short answer is: most of the time time.clock() will be better.
However, if you’re timing some hardware (for example some algorithm you put in the GPU), then time.clock() will get rid of this time and time.time() is the only solution left.
Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, …), this is worse with time.time() but exists also with time.clock(), so you should never run one timing test only, but always run a series of test and look at mean/variance of the times.
One thing to keep in mind:
Changing the system time affects time.time() but not time.clock().
I needed to control some automatic tests executions. If one step of the test case took more than a given amount of time, that TC was aborted to go on with the next one.
But sometimes a step needed to change the system time (to check the scheduler module of the application under test), so after setting the system time a few hours in the future, the TC timeout expired and the test case was aborted. I had to switch from time.time() to time.clock() to handle this properly.
Return the CPU time or real time since the start of the process or since
the first call to clock(). This has as much precision as the system
records.
time() -> floating point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
Usually time() is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)
Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provides NO accuracy because it may manage CPU time.
using time():1 requests, response time:14.1749382019 ms
2 requests, response time:8.01301002502 ms
3 requests, response time:8.01491737366 ms
4 requests, response time:8.41021537781 ms
5 requests, response time:8.38804244995 ms
using clock():
1 requests, response time:10.0 ms
2 requests, response time:0.0 ms
3 requests, response time:0.0 ms
4 requests, response time:10.0 ms
5 requests, response time:0.0 ms
6 requests, response time:0.0 ms
7 requests, response time:0.0 ms
8 requests, response time:0.0 ms
time() has better precision than clock() on Linux. clock() only has precision less than 10 ms. While time() gives prefect precision.
My test is on CentOS 6.4, python 2.6
using time():
1 requests, response time: 14.1749382019 ms
2 requests, response time: 8.01301002502 ms
3 requests, response time: 8.01491737366 ms
4 requests, response time: 8.41021537781 ms
5 requests, response time: 8.38804244995 ms
using clock():
1 requests, response time: 10.0 ms
2 requests, response time: 0.0 ms
3 requests, response time: 0.0 ms
4 requests, response time: 10.0 ms
5 requests, response time: 0.0 ms
6 requests, response time: 0.0 ms
7 requests, response time: 0.0 ms
8 requests, response time: 0.0 ms
As others have noted time.clock() is deprecated in favour of time.perf_counter() or time.process_time(), but Python 3.7 introduces nanosecond resolution timing with time.perf_counter_ns(), time.process_time_ns(), and time.time_ns(), along with 3 other functions.
These 6 new nansecond resolution functions are detailed in PEP 564:
time.clock_gettime_ns(clock_id)
time.clock_settime_ns(clock_id, time:int)
time.monotonic_ns()
time.perf_counter_ns()
time.process_time_ns()
time.time_ns()
These functions are similar to the version without the _ns suffix, but
return a number of nanoseconds as a Python int.
As others have also noted, use the timeit module to time functions and small code snippets.
On Unix time.clock() measures the amount of CPU time that has been used by the current process, so it’s no good for measuring elapsed time from some point in the past. On Windows it will measure wall-clock seconds elapsed since the first call to the function. On either system time.time() will return seconds passed since the epoch.
If you’re writing code that’s meant only for Windows, either will work (though you’ll use the two differently – no subtraction is necessary for time.clock()). If this is going to run on a Unix system or you want code that is guaranteed to be portable, you will want to use time.time().
Short answer: use time.clock() for timing in Python.
On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number.
time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value.
To the best of my understanding, time.clock() has as much precision as your system will allow it.
回答 12
我使用这段代码比较2种方法。我的操作系统是Windows 8,处理器核心i5,RAM 4GB
import time
def t_time():
start=time.time()
time.sleep(0.1)return(time.time()-start)def t_clock():
start=time.clock()
time.sleep(0.1)return(time.clock()-start)
counter_time=0
counter_clock=0for i in range(1,100):
counter_time += t_time()for i in range(1,100):
counter_clock += t_clock()print"time() =",counter_time/100print"clock() =",counter_clock/100
Right answer : They’re both the same length of a fraction.
But which faster if subject is time ?
A little test case :
import timeit
import time
clock_list = []
time_list = []
test1 = """
def test(v=time.clock()):
s = time.clock() - v
"""
test2 = """
def test(v=time.time()):
s = time.time() - v
"""
def test_it(Range) :
for i in range(Range) :
clk = timeit.timeit(test1, number=10000)
clock_list.append(clk)
tml = timeit.timeit(test2, number=10000)
time_list.append(tml)
test_it(100)
print "Clock Min: %f Max: %f Average: %f" %(min(clock_list), max(clock_list), sum(clock_list)/float(len(clock_list)))
print "Time Min: %f Max: %f Average: %f" %(min(time_list), max(time_list), sum(time_list)/float(len(time_list)))
I am not work an Swiss labs but I’ve tested..
Based of this question : time.clock() is better than time.time()
Edit : time.clock() is internal counter so can’t use outside, got limitations max 32BIT FLOAT, can’t continued counting if not store first/last values. Can’t merge another one counter…
On Unix, return the current processor time as a floating point number expressed in seconds.
On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number
print(time.clock()); time.sleep(10); print(time.clock())
# Linux : 0.0382 0.0384 # see Processor Time
# Windows: 26.1224 36.1566 # see Wall-Clock Time
So which function to pick instead?
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.
Use time.process_time()
Wall-Clock Time: This refers to how much time has passed “on a clock hanging on the wall”, i.e. outside real time.
Use time.perf_counter()
time.time() also measures wall-clock time but can be reset, so you could go back in time
time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
I put this timing.py module into my own site-packages directory, and just insert import timing at the top of my module:
import atexit
from time import clock
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
line = "="*40
def log(s, elapsed=None):
print line
print secondsToStr(clock()), '-', s
if elapsed:
print "Elapsed time:", elapsed
print line
print
def endlog():
end = clock()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
def now():
return secondsToStr(clock())
start = clock()
atexit.register(endlog)
log("Start Program")
I can also call timing.log from within my program if there are significant stages within the program I want to show. But just including import timing will print the start and end times, and overall elapsed time. (Forgive my obscure secondsToStr function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)
Note: A Python 3 version of the above code can be found here or here.
$ time -v python yourprogram.py
Command being timed:"python3 yourprogram.py"User time (seconds):0.08System time (seconds):0.02Percent of CPU this job got:98%Elapsed(wall clock) time (h:mm:ss or m:ss):0:00.10Average shared text size (kbytes):0Average unshared data size (kbytes):0Average stack size (kbytes):0Average total size (kbytes):0Maximum resident set size (kbytes):9480Average resident set size (kbytes):0Major(requiring I/O) page faults:0Minor(reclaiming a frame) page faults:1114Voluntary context switches:0Involuntary context switches:22Swaps:0File system inputs:0File system outputs:0Socket messages sent:0Socket messages received:0Signals delivered:0Page size (bytes):4096Exit status:0
$ time -v python yourprogram.py
Command being timed: "python3 yourprogram.py"
User time (seconds): 0.08
System time (seconds): 0.02
Percent of CPU this job got: 98%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 9480
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 1114
Voluntary context switches: 0
Involuntary context switches: 22
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
I really like Paul McGuire’s answer, but I use Python 3. So for those who are interested: here’s a modification of his answer that works with Python 3 on *nix (I imagine, under Windows, that clock() should be used instead of time()):
#python3
import atexit
from time import time, strftime, localtime
from datetime import timedelta
def secondsToStr(elapsed=None):
if elapsed is None:
return strftime("%Y-%m-%d %H:%M:%S", localtime())
else:
return str(timedelta(seconds=elapsed))
def log(s, elapsed=None):
line = "="*40
print(line)
print(secondsToStr(), '-', s)
if elapsed:
print("Elapsed time:", elapsed)
print(line)
print()
def endlog():
end = time()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
start = time()
atexit.register(endlog)
log("Start Program")
If you find this useful, you should still up-vote his answer instead of this one, as he did most of the work ;).
回答 4
import time
start_time = time.clock()
main()print time.clock()- start_time,"seconds"
time.clock() returns the processor time, which allows us to calculate only the time used by this process (on Unix anyway). The documentation says “in any case, this is the function to use for benchmarking Python or timing algorithms”
from datetime import datetime
start_time = datetime.now()# do your work here
end_time = datetime.now()print('Duration: {}'.format(end_time - start_time))
I like the output the datetime module provides, where time delta objects show days, hours, minutes, etc. as necessary in a human-readable way.
For example:
from datetime import datetime
start_time = datetime.now()
# do your work here
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))
Sample output e.g.
Duration: 0:00:08.309267
or
Duration: 1 day, 1:51:24.269711
As J.F. Sebastian mentioned, this approach might encounter some tricky cases with local time, so it’s safer to use:
import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))
You can use the Python profiler cProfile to measure CPU time and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where to start. This answer to another Stack Overflow question is pretty good. It’s always good to have a look in the documentation too.
Here’s an example how to profile a script using cProfile from a command line:
$ time -v python rhtest2.py
Command being timed:"python rhtest2.py"User time (seconds):4.13System time (seconds):0.07Percent of CPU this job got:91%Elapsed(wall clock) time (h:mm:ss or m:ss):0:04.58Average shared text size (kbytes):0Average unshared data size (kbytes):0Average stack size (kbytes):0Average total size (kbytes):0Maximum resident set size (kbytes):0Average resident set size (kbytes):0Major(requiring I/O) page faults:15Minor(reclaiming a frame) page faults:5095Voluntary context switches:27Involuntary context switches:279Swaps:0File system inputs:0File system outputs:0Socket messages sent:0Socket messages received:0Signals delivered:0Page size (bytes):4096Exit status:0
$ time -v python rhtest2.py
Command being timed: "python rhtest2.py"
User time (seconds): 4.13
System time (seconds): 0.07
Percent of CPU this job got: 91%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.58
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 15
Minor (reclaiming a frame) page faults: 5095
Voluntary context switches: 27
Involuntary context switches: 279
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
Deprecated since version 3.3: The behavior of this function depends
on the platform: use perf_counter() or process_time() instead,
depending on your requirements, to have a well-defined behavior.
time.perf_counter()
Return the value (in fractional seconds) of a performance counter,
i.e. a clock with the highest available resolution to measure a short
duration. It does include time elapsed during sleep and is
system-wide.
time.process_time()
Return the value (in fractional seconds) of the sum of the system and
user CPU time of the current process. It does not include time elapsed
during sleep.
import timeit
start = timeit.default_timer()# All the program statements
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+str(execution_time))# It returns time in seconds
def sample_function(start,**kwargs):try:# Your statementsexcept:# except statements run when your statements raise an exception
stop = timeit.default_timer()
execution_time = stop - start
print("Program executed in "+ str(execution_time))
Just use the timeit module. It works with both Python 2 and Python 3.
import timeit
start = timeit.default_timer()
# All the program statements
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+str(execution_time)) # It returns time in seconds
It returns in seconds and you can have your execution time. It is simple, but you should write these in thew main function which starts program execution. If you want to get the execution time even when you get an error then take your parameter “Start” to it and calculate there like:
def sample_function(start,**kwargs):
try:
# Your statements
except:
# except statements run when your statements raise an exception
stop = timeit.default_timer()
execution_time = stop - start
print("Program executed in " + str(execution_time))
回答 10
以下代码段以一种易于阅读的<HH:MM:SS>格式打印经过的时间。
import time
from datetime import timedelta
start_time = time.time()## Perform lots of computations.#
elapsed_time_secs = time.time()- start_time
msg ="Execution took: %s secs (Wall clock time)"% timedelta(seconds=round(elapsed_time_secs))print(msg)
import datetime as dt
import timeit
classTimingManager(object):"""Context Manager used with the statement 'with' to time some execution.
Example:
with TimingManager() as t:
# Code to time
"""
clock = timeit.default_timer
def __enter__(self):"""
"""
self.start = self.clock()
self.log('\n=> Start Timing: {}')return self
def __exit__(self, exc_type, exc_val, exc_tb):"""
"""
self.endlog()returnFalsedef log(self, s, elapsed=None):"""Log current time and elapsed time if present.
:param s: Text to display, use '{}' to format the text with
the current time.
:param elapsed: Elapsed time to display. Dafault: None, no display.
"""print s.format(self._secondsToStr(self.clock()))if(elapsed isnotNone):print'Elapsed time: {}\n'.format(elapsed)def endlog(self):"""Log time for the end of execution with elapsed time.
"""
self.log('=> End Timing: {}', self.now())def now(self):"""Return current elapsed time as hh:mm:ss string.
:return: String.
"""return str(dt.timedelta(seconds = self.clock()- self.start))def _secondsToStr(self, sec):"""Convert timestamp to h:mm:ss string.
:param sec: Timestamp.
"""return str(dt.datetime.fromtimestamp(sec))
I liked Paul McGuire’s answer too and came up with a context manager form which suited my needs more.
import datetime as dt
import timeit
class TimingManager(object):
"""Context Manager used with the statement 'with' to time some execution.
Example:
with TimingManager() as t:
# Code to time
"""
clock = timeit.default_timer
def __enter__(self):
"""
"""
self.start = self.clock()
self.log('\n=> Start Timing: {}')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
"""
self.endlog()
return False
def log(self, s, elapsed=None):
"""Log current time and elapsed time if present.
:param s: Text to display, use '{}' to format the text with
the current time.
:param elapsed: Elapsed time to display. Dafault: None, no display.
"""
print s.format(self._secondsToStr(self.clock()))
if(elapsed is not None):
print 'Elapsed time: {}\n'.format(elapsed)
def endlog(self):
"""Log time for the end of execution with elapsed time.
"""
self.log('=> End Timing: {}', self.now())
def now(self):
"""Return current elapsed time as hh:mm:ss string.
:return: String.
"""
return str(dt.timedelta(seconds = self.clock() - self.start))
def _secondsToStr(self, sec):
"""Convert timestamp to h:mm:ss string.
:param sec: Timestamp.
"""
return str(dt.datetime.fromtimestamp(sec))
# Convert your notebook to a .py script:!jupyter nbconvert --to script example_notebook.ipynb
# Run the example_notebook with -t flag for time%run -t example_notebook
输出量
IPython CPU timings (estimated):
User : 0.00 s.
System : 0.00 s.
Wall time: 0.00 s.
In a cell, you can use Jupyter’s %%time magic command to measure the execution time:
%%time
[ x**2 for x in range(10000)]
Output
CPU times: user 4.54 ms, sys: 0 ns, total: 4.54 ms
Wall time: 4.12 ms
This will only capture the execution time of a particular cell. If you’d like to capture the execution time of the whole notebook (i.e. program), you can create a new notebook in the same directory and in the new notebook execute all cells:
Suppose the notebook above is called example_notebook.ipynb. In a new notebook within the same directory:
# Convert your notebook to a .py script:
!jupyter nbconvert --to script example_notebook.ipynb
# Run the example_notebook with -t flag for time
%run -t example_notebook
Output
IPython CPU timings (estimated):
User : 0.00 s.
System : 0.00 s.
Wall time: 0.00 s.
from line_profiler importLineProfilerimport random
def do_stuff(numbers):
s = sum(numbers)
l =[numbers[i]/43for i in range(len(numbers))]
m =['hello'+str(numbers[i])for i in range(len(numbers))]
numbers =[random.randint(1,100)for i in range(1000)]
lp =LineProfiler()
lp_wrapper = lp(do_stuff)
lp_wrapper(numbers)
lp.print_stats()
结果将是:
Timer unit:1e-06 s
Total time:0.000649 s
File:<ipython-input-2-2e060b054fea>Function: do_stuff at line 4Line# Hits Time Per Hit % Time Line Contents==============================================================4def do_stuff(numbers):511010.01.5 s = sum(numbers)61186186.028.7 l =[numbers[i]/43for i in range(len(numbers))]71453453.069.8 m =['hello'+str(numbers[i])for i in range(len(numbers))]
line_profiler will profile the time individual lines of code take to execute. The profiler is implemented in C via Cython in order to reduce the overhead of profiling.
from line_profiler import LineProfiler
import random
def do_stuff(numbers):
s = sum(numbers)
l = [numbers[i]/43 for i in range(len(numbers))]
m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
numbers = [random.randint(1,100) for i in range(1000)]
lp = LineProfiler()
lp_wrapper = lp(do_stuff)
lp_wrapper(numbers)
lp.print_stats()
The results will be:
Timer unit: 1e-06 s
Total time: 0.000649 s
File: <ipython-input-2-2e060b054fea>
Function: do_stuff at line 4
Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 def do_stuff(numbers):
5 1 10 10.0 1.5 s = sum(numbers)
6 1 186 186.0 28.7 l = [numbers[i]/43 for i in range(len(numbers))]
7 1 453 453.0 69.8 m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
And to use it, just call it before the code to measure to retrieve function timing, and then call the function after the code with comments. The time will appear in front of the comments. For example:
I was having the same problem in many places, so I created a convenience package horology. You can install it with pip install horology and then do it in the elegant way:
from horology import Timing
with Timing(name='Important calculations: '):
prepare()
do_your_stuff()
finish_sth()
will output:
Important calculations: 12.43 ms
Or even simpler (if you have one function):
from horology import timed
@timed
def main():
...
will output:
main: 7.12 h
It takes care of units and rounding. It works with python 3.6 or newer.
Timeit is a class in Python used to calculate the execution time of small blocks of code.
Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.
A sample of the code is as follows:
from timeit import default_timer as timer
start= timer()
# Some logic
end = timer()
print("Time taken:", end-start)
import timeit
code_to_test ="""
a = range(100000)
b = []
for i in a:
b.append(i*2)
"""
elapsed_time = timeit.timeit(code_to_test, number=500)print(elapsed_time)# 10.159821493085474
import timeit
code_to_test = """
a = range(100000)
b = []
for i in a:
b.append(i*2)
"""
elapsed_time = timeit.timeit(code_to_test, number=500)
print(elapsed_time)
# 10.159821493085474
Wrap all your code, including any imports you may have, inside code_to_test.
number argument specifies the amount of times the code should repeat.
import time
now = time.time()
future = now +10
step =4# Why 4 steps? Because until here already four operations executedwhile time.time()< future:
step +=3# Why 3 again? Because a while loop executes one comparison and one plus equal statement
step +=4# Why 3 more? Because one comparison starting while when time is over plus the final assignment of step + 1 and print statementprint(str(int(step /10))+" steps per second")
The time of a Python program’s execution measure could be inconsistent depending on:
Same program can be evaluated using different algorithms
Running time varies between algorithms
Running time varies between implementations
Running time varies between computers
Running time is not predictable based on small inputs
This is because the most effective way is using the “Order of Growth” and learn the Big “O” notation to do it properly.
Anyway, you can try to evaluate the performance of any Python program in specific machine counting steps per second using this simple algorithm:
adapt this to the program you want to evaluate
import time
now = time.time()
future = now + 10
step = 4 # Why 4 steps? Because until here already four operations executed
while time.time() < future:
step += 3 # Why 3 again? Because a while loop executes one comparison and one plus equal statement
step += 4 # Why 3 more? Because one comparison starting while when time is over plus the final assignment of step + 1 and print statement
print(str(int(step / 10)) + " steps per second")
回答 24
您只需在Python中执行此操作即可。无需使其变得复杂。
import time
start = time.localtime()
end = time.localtime()"""Total execution time in seconds$ """print(end.tm_sec - start.tm_sec)
from humanfriendly import format_timespan
import time
begin_time = time.time()# Put your code here
end_time = time.time()- begin_time
print("Total execution time: ", format_timespan(end_time))
First, install humanfriendly package by opening Command Prompt (CMD) as administrator and type there –
pip install humanfriendly
Code:
from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))
If you want to measure time in microseconds, then you can use the following version, based completely on the answers of Paul McGuire and Nicojo – it’s Python 3 code. I’ve also added some colour to it:
The time module provides functions that tells us the time in “seconds since the epoch” as well as other utilities.
import time
Unix Epoch Time
This is the format you should get timestamps in for saving in databases. It is a simple floating point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970 00:00:00, and it is memory light relative to the other representations of time we’ll be looking at next:
>>> time.time()
1424233311.771502
This timestamp does not account for leap-seconds, so it’s not linear – leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.
This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you’ll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).
time.ctime
You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don’t rely on this to be standard across all systems, as I’ve seen others expect). This is typically user friendly, but doesn’t typically result in strings one can sort chronologically:
>>> time.ctime()
'Tue Feb 17 23:21:56 2015'
You can hydrate timestamps into human readable form with ctime as well:
>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'
This conversion is also not good for record-keeping (except in text that will only be parsed by humans – and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).
datetime module
The datetime module is also quite useful here:
>>> import datetime
datetime.datetime.now
The datetime.now is a class method that returns the current time. It uses the time.localtime without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a str), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:
UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.)
datetime timezone aware
However, none of the datetime objects we’ve created so far can be easily converted to various timezones. We can solve that problem with the pytz module:
>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)
Equivalently, in Python 3 we have the timezone class with a utc timezone instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy pytz module is left as an exercise to the reader):
You can also make a naive datetime object aware with the pytz timezone localize method, or by replacing the tzinfo attribute (with replace, this is done blindly), but these are more last resorts than best practices:
The pytz module allows us to make our datetime objects timezone aware and convert the times to the hundreds of timezones available in the pytz module.
One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.
The other ways of viewing times are much more error prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.
If you’re displaying the time with Python for the user, ctime works nicely, not in a table (it doesn’t typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime object.
import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)print(tree.xpath('//html//body//h3//pre/text()')[1])
Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?
import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])
If you live in the D.C. area (like me) the latency might not be too bad…
import pandas as pd
print(pd.datetime.now())print(pd.datetime.now().date())print(pd.datetime.now().year)print(pd.datetime.now().month)print(pd.datetime.now().day)print(pd.datetime.now().hour)print(pd.datetime.now().minute)print(pd.datetime.now().second)print(pd.datetime.now().microsecond)
>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11
Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python “datetime” documentation here).
datetime.now() returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions (“fall back”). To avoid ambiguity either UTC timezone should be used:
Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):
from datetime import datetime, timezone
now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00
回答 17
import datetime
date_time = datetime.datetime.now()
date = date_time.date()# Gives the date
time = date_time.time()# Gives the timeprint date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
Do dir(date) or any variables including the package. You can get all the attributes and methods associated with the variable.
回答 18
>>>import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())>>>print time
'00:21:38:20S'
By default, now() function returns output in the YYYY-MM-DD HH:MM:SS:MS format. Use the below sample script to get the current date and time in a Python script and print results on the screen. Create file getDateTime1.py with the below content.
This question doesn’t need a new answer just for the sake of it … a shiny new-ish toy/module, however, is enough justification. That being the Pendulum library, which appears to do the sort of things which arrow attempted, except without the inherent flaws and bugs which beset arrow.
For instance, the answer to the original question:
There’s a lot of standards which need addressing, including multiple RFCs and ISOs, to worry about. Ever get them mixed up; not to worry, take a little look into dir(pendulum.constants) There’s a bit more than RFC and ISO formats there, though.
When we say local, though what do we mean? Well I mean:
Presumably most of the rest of you mean somewhere else.
And on it goes. Long story short: Pendulum attempts to do for date and time what requests did for HTTP. It’s worth consideration, particularly for both its ease of use and extensive documentation.
arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'
回答 23
我想用毫秒来获取时间。一种简单的获取方法:
import time, datetime
print(datetime.datetime.now().time())# 11:20:08.272239# Or in a more complicated wayprint(datetime.datetime.now().time().isoformat())# 11:20:08.272239print(datetime.datetime.now().time().strftime('%H:%M:%S.%f'))# 11:20:08.272239# But do not use this:print(time.strftime("%H:%M:%S.%f", time.localtime()), str)# 11:20:08.%f
但是我只想毫秒,对不对?获得它们的最短方法:
import time
time.strftime("%H:%M:%S", time.localtime())+'.%d'%(time.time()%1*1000)# 11:34:23.751
I want to get the time with milliseconds. A simple way to get them:
import time, datetime
print(datetime.datetime.now().time()) # 11:20:08.272239
# Or in a more complicated way
print(datetime.datetime.now().time().isoformat()) # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239
# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str) # 11:20:08.%f
But I want only milliseconds, right? The shortest way to get them:
Because no one has mentioned it yet, and this is something I ran into recently… a pytz timezone’s fromutc() method combined with datetime’s utcnow() is the best way I’ve found to get a useful current time (and date) in any timezone.
This question is for Python but since Django is one of the most widely used frameworks for Python, its important to note that if you are using Django you can always use timezone.now() instead of datetime.datetime.now(). The former is timezone ‘aware’ while the latter is not.