标签归档:time

如何在python中获取当前时间并分解为年,月,日,小时,分钟?

问题:如何在python中获取当前时间并分解为年,月,日,小时,分钟?

我想获得当前时间在Python,并将它们分配到变量喜欢yearmonthdayhourminute。如何在Python 2.7中完成?

I would like to get the current time in Python and assign them into variables like year, month, day, hour, minute. How can this be done in Python 2.7?


回答 0

datetime模块是您的朋友:

import datetime
now = datetime.datetime.now()
print now.year, now.month, now.day, now.hour, now.minute, now.second
# 2015 5 6 8 53 40

您不需要单独的变量,返回datetime对象上的属性就可以满足您的所有需求。

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

You don’t need separate variables, the attributes on the returned datetime object have all you need.


回答 1

这是一个单线,最大字符数不超过80个字符。

import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())

Here’s a one-liner that comes in just under the 80 char line max.

import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())

回答 2

tzamandatetime答案要干净得多,但是您可以使用原始的python 模块来实现:time

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers

输出:

[2016, 3, 11, 8, 29, 47]

The datetime answer by tzaman is much cleaner, but you can do it with the original python time module:

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers

Output:

[2016, 3, 11, 8, 29, 47]

回答 3

通过解压缩timetupledatetime对象,您应该得到想要的东西:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

By unpacking timetuple of datetime object, you should get what you want:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

回答 4

对于python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)

For python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)

回答 5

让我们看看如何从当前时间获取并打印python中的日,月,年:

import datetime

now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)

print('day_month_year: ' + day_month_year)

结果:

day_month_year: 2019-03-26

Let’s see how to get and print day,month,year in python from current time:

import datetime

now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)

print('day_month_year: ' + day_month_year)

result:

day_month_year: 2019-03-26

回答 6

import time
year = time.strftime("%Y") # or "%y"
import time
year = time.strftime("%Y") # or "%y"

回答 7

三个用于访问和操纵日期和时间的库,即日期时间,箭头和摆锤,都使这些项在命名元组中可用,命名元组的元素可通过名称或索引访问。此外,可以完全相同的方式访问项目。(我想如果我更聪明,我不会感到惊讶。)

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

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

注意:可以将时间戳传递给gmtime,默认为time()返回的当前时间

eg.
gmtime(1521174681)

参见struct_time

You can use 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

Note: A time stamp can be passed to gmtime, default is current time as returned by time()

eg.
gmtime(1521174681)

See struct_time


回答 9

这是一个比较老的问题,但是我想出了一个我认为其他人可能会喜欢的解决方案。

def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
               "month",
               "day",
               "hour",
               "min",
               "sec",
               "weekday",
               "md",
               "yd"]
return dict(zip(field_names, t))

timetuple()可以与另一个数组一起压缩,这将创建带标签的元组。将其转换为字典,然后可以使用生成的产品get_current_datetime_as_dict()['year']

这比这里的其他一些解决方案有更多的开销,但是我发现能够在代码中为清楚起见而访问命名值真是太好了。

This is an older question, but I came up with a solution I thought others might like.

def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
               "month",
               "day",
               "hour",
               "min",
               "sec",
               "weekday",
               "md",
               "yd"]
return dict(zip(field_names, t))

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.


回答 10

您可以使用datetime模块获取Python 2.7中的当前日期和时间

import datetime
print datetime.datetime.now()

输出:

2015-05-06 14:44:14.369392

you can use datetime module to get current Date and Time in Python 2.7

import datetime
print datetime.datetime.now()

Output :

2015-05-06 14:44:14.369392

time.sleep —休眠线程或进程?

问题:time.sleep —休眠线程或进程?

在Python for * nix中,是否time.sleep()阻塞线程或进程?

In Python for *nix, does time.sleep() block the thread or the process?


回答 0

它阻塞线程。如果在Python源代码中查看Modules / timemodule.c,您会看到在调用中floatsleep(),睡眠操作的实质部分包装在Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS块中,从而允许其他线程在当前线程继续执行一睡觉。您也可以使用简单的python程序进行测试:

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

将打印:

>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102

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

Which will print:

>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102

回答 1

它只会休眠线程,除非您的应用程序只有一个线程,在这种情况下,它将休眠线程并有效地进程。

睡眠中的python文档未指定此内容,因此我当然可以理解混淆!

http://docs.python.org/2/library/time.html

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!

http://docs.python.org/2/library/time.html


回答 2

只是线程。

Just the thread.


回答 3

该线程将阻塞,但是该进程仍然有效。

在单线程应用程序中,这意味着您在睡眠时一切都被阻止了。在多线程应用程序中,只有您显式“睡眠”的线程将被阻塞,其他线程仍在进程中运行。

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.


回答 4

只有线程,除非您的进程具有单个线程。

Only the thread unless your process has a single thread.


回答 5

进程本身无法运行。关于执行,进程只是线程的容器。这意味着您根本无法暂停该过程。它根本不适用于过程。

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.


回答 6

如果它在同一线程中执行,则它将阻塞一个线程,如果不是从主代码中执行,则它将阻塞该线程

it blocks a thread if it is executed in the same thread not if it is executed from the main code


在Python中将N秒添加到datetime.time的标准方法是什么?

问题:在Python中将N秒添加到datetime.time的标准方法是什么?

给定datetime.timePython中的值,是否有标准的方法向其添加整数秒,例如11:34:59+ 3 = 11:35:02

这些明显的想法行不通:

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

最后,我编写了这样的函数:

def add_secs_to_time(timeval, secs_to_add):
    secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
    secs += secs_to_add
    return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)

我不禁以为我缺少一种更简单的方法来做到这一点。

有关

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'

In the end I have written functions like this:

def add_secs_to_time(timeval, secs_to_add):
    secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
    secs += secs_to_add
    return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)

I can’t help thinking that I’m missing an easier way to do this though.

Related


回答 0

您可以将完整datetime变量与一起使用timedelta,并通过提供一个虚拟日期,然后使用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())

得出两个值,相隔三秒:

11:34:59
11:35:02

您也可以选择更具可读性的

b = a + datetime.timedelta(seconds=3)

如果你这么倾向。


如果您追求的是可以执行此操作的函数,则可以使用addSecs以下方法进行研究:

import datetime

def addSecs(tm, secs):
    fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
    fulldate = fulldate + datetime.timedelta(seconds=secs)
    return fulldate.time()

a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)

输出:

 09:11:55.775695
 09:16:55

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:

import datetime

def addSecs(tm, secs):
    fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
    fulldate = fulldate + datetime.timedelta(seconds=secs)
    return fulldate.time()

a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)

This outputs:

 09:11:55.775695
 09:16:55

回答 1

如此处其他人所述,您可以在整个过程中使用完整的datetime对象:

from datetime import datetime, date, time, timedelta
sometime = time(8,00) # 8am
later = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()

但是,我认为值得解释为什么需要完整的datetime对象。考虑如果我在下午11点增加2个小时会发生什么情况。正确的行为是什么?有一个exceptions,因为您的时间不能超过晚上11:59?它应该回绕吗?

不同的程序员会期望不同的东西,因此他们选择的任何结果都会使很多人感到惊讶。更糟糕的是,程序员最初编写的代码在最初测试时就可以正常工作,然后通过做一些意想不到的事情而使代码中断。这非常糟糕,这就是为什么不允许您向时间对象添加timedelta对象的原因。

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)

One little thing, might add clarity to override the default value for seconds

>>> b = a + datetime.timedelta(seconds=3000)
>>> b
datetime.datetime(1, 1, 1, 12, 24, 59)

回答 3

感谢@Pax Diablo,@ bvmou和@Arachnid建议在整个过程中使用完整的日期时间。如果我必须从外部来源接受datetime.time对象,那么这似乎是一种替代add_secs_to_time()功能:

def add_secs_to_time(timeval, secs_to_add):
    dummy_date = datetime.date(1, 1, 1)
    full_datetime = datetime.datetime.combine(dummy_date, timeval)
    added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
    return added_datetime.time()

此冗长的代码可以压缩为以下形式:

(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()

但我想我还是要将其包装在一个函数中,以确保代码清晰。

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:

def add_secs_to_time(timeval, secs_to_add):
    dummy_date = datetime.date(1, 1, 1)
    full_datetime = datetime.datetime.combine(dummy_date, timeval)
    added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
    return added_datetime.time()

This verbose code can be compressed to this one-liner:

(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()

but I think I’d want to wrap that up in a function for code clarity anyway.


回答 4

如果值得在您的项目中添加另一个文件/依赖项,那么我刚刚编写了一个很小的小类,它datetime.time具有算术能力。当您经过午夜时,它会绕零。现在,“从现在开始24小时将是几点钟”有很多特殊情况,包括夏时制,leap秒,历史时区更改等。但是有时候您确实确实需要简单的案例,这就是这样做的目的。

您的示例将写为:

>>> import datetime
>>> import nptime
>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)
nptime(11, 35, 2)

nptime继承自datetime.time,因此任何这些方法也应该可用。

可以从PyPi以nptime(“非修整时间”)或在GitHub上获得:https : //github.com/tgs/nptime

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.

Your example would be written:

>>> import datetime
>>> import nptime
>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)
nptime(11, 35, 2)

nptime inherits from datetime.time, so any of those methods should be usable, too.

It’s available from PyPi as nptime (“non-pedantic time”), or on GitHub: https://github.com/tgs/nptime


回答 5

您不能简单地添加数字,datetime因为不清楚使用的单位是秒,小时,周…

timedelta用于日期和时间操作的类。datetime减去datetimeGives timedeltadatetimePlus timedeltaGives datetimedatetime虽然两个对象可以添加,但不能添加两个对象timedelta

创建timedelta要添加多少秒的datetime对象并将其添加到对象:

>>> from datetime import datetime, timedelta
>>> t = datetime.now() + timedelta(seconds=3000)
>>> print(t)
datetime.datetime(2018, 1, 17, 21, 47, 13, 90244)

C ++中有相同的概念:std::chrono::duration

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:

>>> from datetime import datetime, timedelta
>>> t = datetime.now() + timedelta(seconds=3000)
>>> print(t)
datetime.datetime(2018, 1, 17, 21, 47, 13, 90244)

There is same concept in C++: std::chrono::duration.


回答 6

为了完整起见,这是使用它的方式arrow(Python的更好的日期和时间):

sometime = arrow.now()
abitlater = sometime.shift(seconds=3)

For completeness’ sake, here’s the way to do it with arrow (better dates and times for Python):

sometime = arrow.now()
abitlater = sometime.shift(seconds=3)

回答 7

尝试添加datetime.datetimedatetime.timedelta。如果只需要时间部分,则可以time()在结果datetime.datetime对象上调用方法以获取它。

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.


回答 8

老问题了,但我想我会抛出一个处理时区的函数。关键部分是将datetime.time对象的tzinfo属性传递到Combine中,然后在结果虚拟日期时间上使用timetz()而不是time()。此答案部分受此处其他答案的启发。

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

这是一个非常简单的测试用例类(使用内置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()

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

如何使用timeit模块

问题:如何使用timeit模块

我了解做什么的概念,timeit但不确定如何在代码中实现。

我怎样才能比较两个功能,比方说insertion_sorttim_sort,用timeit

I understand the concept of what timeit does but I am not sure how to implement it in my code.

How can I compare two functions, say insertion_sort and tim_sort, with timeit?


回答 0

timeit的工作方式是运行一次安装代码,然后重复调用一系列语句。因此,如果要测试排序,则需要格外小心,以免就地进行一次排序不会影响已排序数据的下一遍(这当然会使Timsort发光,因为它表现最佳当数据已经部分排序时)。

这是有关如何设置排序测试的示例:

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

请注意,这一系列语句在每次通过时都会对未排序的数据进行全新复制。

另外,请注意运行测量套件七次并仅保留最佳时间的计时技术-这确实可以帮助减少由于系统上正在运行其他进程而导致的测量失真。

这些是我正确使用timeit的技巧。希望这可以帮助 :-)

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


回答 1

如果要timeit在交互式Python会话中使用,有两个方便的选项:

  1. 使用IPython Shell。它具有方便的%timeit特殊功能:

    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
  2. 在标准的Python解释器中,您可以通过__main__在setup语句中导入它们来访问在交互式会话期间先前定义的函数和其他名称:

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

  1. 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
    
  2. 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]
    

回答 2

我会告诉您一个秘密:最好的使用方法timeit是在命令行上。

在命令行上,进行timeit适当的统计分析:它告诉您最短运行花费了多长时间。这很好,因为所有计时错误都是正的。因此,最短的时间误差最小。没有办法得到负错误,因为计算机的计算速度永远不可能超过其计算速度!

因此,命令行界面:

%~> python -m timeit "1 + 2"
10000000 loops, best of 3: 0.0468 usec per loop

这很简单,是吗?

您可以设置以下内容:

%~> python -m timeit -s "x = range(10000)" "sum(x)"
1000 loops, best of 3: 543 usec per loop

也是有用的!

如果需要多行,则可以使用外壳程序的自动延续或使用单独的参数:

%~> python -m timeit -s "x = range(10000)" -s "y = range(100)" "sum(x)" "min(y)"
1000 loops, best of 3: 554 usec per loop

这给出了一个设置

x = range(1000)
y = range(100)

和时代

sum(x)
min(y)

如果您想要更长的脚本,则可能会倾向于timeit使用Python脚本。我建议避免这种情况,因为在命令行上分析和计时会更好。相反,我倾向于制作shell脚本:

 SETUP="

 ... # lots of stuff

 "

 echo Minmod arr1
 python -m timeit -s "$SETUP" "Minmod(arr1)"

 echo pure_minmod arr1
 python -m timeit -s "$SETUP" "pure_minmod(arr1)"

 echo better_minmod arr1
 python -m timeit -s "$SETUP" "better_minmod(arr1)"

 ... etc

由于要进行多次初始化,因此可能需要更长的时间,但是通常这没什么大不了的。


但是,如果timeit在模块内部使用该怎么办?

好吧,简单的方法是:

def function(...):
    ...

timeit.Timer(function).timeit(number=NUMBER)

这样您就可以累积(而不是最短!)时间来运行该次数。

为了获得良好的分析效果,请使用.repeat并采取以下最低限度的措施:

min(timeit.Timer(function).repeat(repeat=REPEATS, number=NUMBER))

通常应将此与结合使用,functools.partial而不是lambda: ...降低开销。因此,您可能会遇到以下情况:

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

您也可以:

timeit.timeit("...", setup="from __main__ import ...", number=NUMBER)

这将使您从命令行更接近界面,但是方式要少得多。将"from __main__ import ..."让您使用代码从您的主模块所创造的人工环境内timeit

值得注意的是,这是一个方便包装Timer(...).timeit(...),因此在时间安排上并不是特别好。我个人更喜欢使用Timer(...).repeat(...)上面显示的内容。


警告事项

timeit到处都有一些警告。

  • 开销不占。说您要计时x += 1,找出加法需要多长时间:

    >>> python -m timeit -s "x = 0" "x += 1"
    10000000 loops, best of 3: 0.0476 usec per loop

    好吧,这不是 0.0476 µs。您只知道它比这还。所有错误均为正。

    因此,尝试找到开销:

    >>> python -m timeit -s "x = 0" ""      
    100000000 loops, best of 3: 0.014 usec per loop

    仅从定时开始,这就是30%的开销!这会大大歪曲相对的时间安排。但是您只真正关心添加的时间。查找时间x也需要包含在开销中:

    >>> python -m timeit -s "x = 0" "x"
    100000000 loops, best of 3: 0.0166 usec per loop

    差别不大,但是就在那里。

  • 变异方法很危险。

    >>> python -m timeit -s "x = [0]*100000" "while x: x.pop()"
    10000000 loops, best of 3: 0.0436 usec per loop

    但这是完全错误的! x是第一次迭代后的空列表。您需要重新初始化:

    >>> python -m timeit "x = [0]*100000" "while x: x.pop()"
    100 loops, best of 3: 9.79 msec per loop

    但是那样您就会有很多开销。分别说明。

    >>> python -m timeit "x = [0]*100000"                   
    1000 loops, best of 3: 261 usec per loop

    请注意,在这里减去开销是合理的,仅是因为开销只是时间的一小部分。

    对于你的榜样,值得一提的是,这两个插入排序和蒂姆排序有完全不同寻常的已排序的列表时序行为。这意味着,random.shuffle如果您想避免破坏时间安排,就需要进行两次排序。

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:

 SETUP="

 ... # lots of stuff

 "

 echo Minmod arr1
 python -m timeit -s "$SETUP" "Minmod(arr1)"

 echo pure_minmod arr1
 python -m timeit -s "$SETUP" "pure_minmod(arr1)"

 echo better_minmod arr1
 python -m timeit -s "$SETUP" "better_minmod(arr1)"

 ... etc

This can take a bit longer due to the multiple initialisations, but normally that’s not a big deal.


But what if you want to use timeit inside your module?

Well, the simple way is to do:

def function(...):
    ...

timeit.Timer(function).timeit(number=NUMBER)

and that gives you cumulative (not minimum!) time to run that number of times.

To get a good analysis, use .repeat and take the minimum:

min(timeit.Timer(function).repeat(repeat=REPEATS, number=NUMBER))

You should normally combine this with functools.partial instead of lambda: ... to lower overhead. Thus you could have something like:

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

You can also do:

timeit.timeit("...", setup="from __main__ import ...", number=NUMBER)

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.


回答 3

如果要快速比较两个代码/功能块,可以执行以下操作:

import timeit

start_time = timeit.default_timer()
func1()
print(timeit.default_timer() - start_time)

start_time = timeit.default_timer()
func2()
print(timeit.default_timer() - start_time)

If you want to compare two blocks of code / functions quickly you could do:

import timeit

start_time = timeit.default_timer()
func1()
print(timeit.default_timer() - start_time)

start_time = timeit.default_timer()
func2()
print(timeit.default_timer() - start_time)

回答 4

我发现使用timeit的最简单方法是从命令行:

给定test.py

def InsertionSort(): ...
def TimSort(): ...

运行timeit是这样的:

% python -mtimeit -s'import test' 'test.InsertionSort()'
% python -mtimeit -s'import test' 'test.TimSort()'

I find the easiest way to use timeit is from the command line:

Given test.py:

def InsertionSort(): ...
def TimSort(): ...

run timeit like this:

% python -mtimeit -s'import test' 'test.InsertionSort()'
% python -mtimeit -s'import test' 'test.TimSort()'

回答 5

对我来说,这是最快的方法:

import timeit
def foo():
    print("here is my code to time...")


timeit.timeit(stmt=foo, number=1234567)

for me, this is the fastest way:

import timeit
def foo():
    print("here is my code to time...")


timeit.timeit(stmt=foo, number=1234567)

回答 6

# Генерация целых чисел

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)
# Генерация целых чисел

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)

回答 7

这很好用:

  python -m timeit -c "$(cat file_name.py)"

This works great:

  python -m timeit -c "$(cat file_name.py)"

回答 8

让我们在以下每个目录中设置相同的字典并测试执行时间。

setup参数基本上是在设置字典

编号是要运行的代码1000000次。不是设置而是stmt

运行此命令时,您可以看到索引比获取索引快得多。您可以多次运行以查看。

该代码基本上试图获取字典中c的值。

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

这是我的结果,您的结果会有所不同。

按索引:0.20900007452246427

通过获取:0.54841166886888

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


def oct(x):
   return x*x


timeit.Timer("for x in range(100): oct(x)", "gc.enable()").timeit()

回答 11

内置的timeit模块在IPython命令行中效果最佳。

要从模块内计时功能:

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

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                                                                                        

Example of how to use Python REPL interpreter with function that accepts parameters.

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

回答 13

您将创建两个函数,然后运行与此类似的操作。请注意,您要选择相同的执行/运行次数来比较apple与apple。
这已在Python 3.7下进行了测试。

这是易于复制的代码

!/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")

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

使用“时间”模块测量经过时间

问题:使用“时间”模块测量经过时间

使用python中的时间模块,可以测量经过的时间吗?如果是这样,我该怎么做?

我需要这样做,以便如果光标在小部件中已存在一定时间,则会发生事件。

With the Time module in python is it possible to measure elapsed time? If so, how do I do that?

I need to do this so that if the cursor has been in a widget for a certain duration an event happens.


回答 0

start_time = time.time()
# your code
elapsed_time = time.time() - start_time

您还可以编写简单的装饰器来简化各种功能的执行时间的度量:

import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()

        ret = fn(*args, **kwargs)

        elapsed_time = time.time() - start_time

        if fn.__name__ not in PROF_DATA:
            PROF_DATA[fn.__name__] = [0, []]
        PROF_DATA[fn.__name__][0] += 1
        PROF_DATA[fn.__name__][1].append(elapsed_time)

        return ret

    return with_profiling

def print_prof_data():
    for fname, data in PROF_DATA.items():
        max_time = max(data[1])
        avg_time = sum(data[1]) / len(data[1])
        print "Function %s called %d times. " % (fname, data[0]),
        print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
    global PROF_DATA
    PROF_DATA = {}

用法:

@profile
def your_function(...):
    ...

您可以同时分析多个功能。然后要打印测量值,只需调用print_prof_data():

start_time = time.time()
# your code
elapsed_time = time.time() - start_time

You can also write simple decorator to simplify measurement of execution time of various functions:

import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()

        ret = fn(*args, **kwargs)

        elapsed_time = time.time() - start_time

        if fn.__name__ not in PROF_DATA:
            PROF_DATA[fn.__name__] = [0, []]
        PROF_DATA[fn.__name__][0] += 1
        PROF_DATA[fn.__name__][1].append(elapsed_time)

        return ret

    return with_profiling

def print_prof_data():
    for fname, data in PROF_DATA.items():
        max_time = max(data[1])
        avg_time = sum(data[1]) / len(data[1])
        print "Function %s called %d times. " % (fname, data[0]),
        print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
    global PROF_DATA
    PROF_DATA = {}

Usage:

@profile
def your_function(...):
    ...

You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():


回答 1

time.time() 会做的工作。

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

您可能想看一下这个问题,但是我认为没有必要。

time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don’t think it will be necessary.


回答 2

对于想要更好格式的用户,

import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))

将打印出2秒钟:

'00:00:02'

一秒钟持续7分钟:

'00:07:01'

请注意,使用gmtime的最小时间单位是秒。如果需要微秒,请考虑以下事项:

import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds) 

strftime 文档

For users that want better formatting,

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) 

strftime documentation


回答 3

为了获得最佳的经过时间度量(自Python 3.3起),请使用time.perf_counter()

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟以测量较短的持续时间。它确实包括整个系统的睡眠时间。返回值的参考点是不确定的,因此仅连续调用结果之间的差有效。

对于小时/天量级的测量,您不必担心亚秒级分辨率,请time.monotonic()改用。

返回单调时钟的值(以小数秒为单位),即不能向后移动的时钟。时钟不受系统时钟更新的影响。返回值的参考点是不确定的,因此仅连续调用结果之间的差有效。

在许多实现中,这些实际上可能是同一件事。

在3.3之前,您会受困于time.clock()

在Unix上,以秒为单位返回当前处理器时间,以浮点数表示。精度,实际上是“处理器时间”含义的确切定义,取决于同名C函数的精度。

在Windows上,此函数将基于Win32函数QueryPerformanceCounter()返回自第一次调用此函数以来经过的时间(以秒为单位)的浮点数。分辨率通常优于一微秒。


Python 3.7更新

PEP 564是Python 3.7中的新功能-添加具有纳秒分辨率的新时间函数。

使用这些可以进一步消除舍入和浮点错误,尤其是在测量周期很短或应用程序(或Windows计算机)正在长时间运行时。

perf_counter()大约100天后,分辨率开始下降。因此,例如,经过一年的正常运行时间后,它可以测量的最短间隔(大于0)将大于开始时的间隔。


Python 3.8更新

time.clock 现在不见了。

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.

Before 3.3, you’re stuck with time.clock().

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

会打印

00:03:15

如果超过24小时

25:33:57

这是受到罗格·霍夫斯特(Rutger Hofste)的回答的启发。谢谢罗格!

For a longer period.

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

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

然后,可以使用Timer类,如下所示:

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

结果如下:

素数:[2、3、5、7、11、13、17、19、23、29、31、37、41、43、47、53、59、61、67、71、73、79、83、89 ,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227 ,229、233、239、241、251、257、263、269、271、277、281、283、293、307、311、313、317、331、337、347、349、353、359、367、373 ,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499]

计算一些质数所需的时间:5.01704216003418ms

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

The result is the following:

Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]

Elapsed time to compute some prime numbers: 5.01704216003418ms


回答 7

Vadim Shender的反应很棒。您还可以使用以下更简单的装饰器:

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

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.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
  • 处理器时间:这是该特定进程在CPU上主动执行所花费的时间。睡眠,等待Web请求或仅执行其他进程的时间不会对此有所帮助。

    • 采用 time.process_time()
  • 墙上时钟时间:这指的是“挂在墙上的时钟上”经过了多少时间,即不是实时时间。

    • 采用 time.perf_counter()

      • time.time() 还可以测量挂钟时间,但可以重置,因此您可以返回到过去
      • time.monotonic() 无法重置(单调=仅前进),但精度低于 time.perf_counter()

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)

Here is an update to Vadim Shender’s clever code with tabular output:

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)

Python的time.time()返回本地或UTC时间戳吗?

问题:Python的time.time()返回本地或UTC时间戳吗?

是否time.time()Python的时间模块系统返回的时间或UTC时间?

Does time.time() in the Python time module return the system’s time or the time in UTC?


回答 0

time.time()函数返回自纪元以来的秒数,以秒为单位。请注意,“时代”定义为UTC的1970年1月1日开始。因此,以UTC定义时代,并确定全球时间。无论您身在何处,“ time.time()”都会在同一时刻返回相同的值。

这是我在计算机上运行的一些示例输出,也将其转换为字符串。

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

ts变量是在几秒钟内返回的时间。然后,我使用datetime库将其转换为字符串,从而使其成为人类可读的字符串。

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.


回答 1

这是用于时间戳记文本形式可以在文本文件中使用。(问题的标题在过去是不同的,因此对该答案的介绍进行了更改,以阐明如何将其解释为时间。[2016年1月14日更新])

您可以使用.now().utcnow()来将时间戳记作为字符串获取datetime.datetime

>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000

now不同之处utcnow与预期的不同-否则它们以相同的方式工作:

>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000

您可以将时间戳显式呈现给字符串:

>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'

或者,您甚至可以更明确地以自己喜欢的方式格式化时间戳记:

>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'

如果要使用ISO格式,请使用.isoformat()对象的方法:

>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'

您可以在变量中使用这些变量来进行计算和打印,而无需进行转换。

>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980

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:

>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000

The now differs from utcnow as expected — otherwise they work the same way:

>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000

You can render the timestamp to the string explicitly:

>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'

Or you can be even more explicit to format the timestamp the way you like:

>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'

If you want the ISO format, use the .isoformat() method of the object:

>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'

You can use these in variables for calculations and printing without conversions.

>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980

回答 2

根据#squiguy的答案,要获得真实的时间戳,我会键入从float转换的时间戳。

>>> import time
>>> ts = int(time.time())
>>> print(ts)
1389177318

至少那是概念。

Based on the answer from #squiguy, to get a true timestamp I would type cast it from float.

>>> import time
>>> ts = int(time.time())
>>> print(ts)
1389177318

At least that’s the concept.


回答 3

答案可能不是两者皆有。

  • 都不:time.time()返回距新纪元已过去的秒数。结果不取决于时区,因此它既不是UTC也不是本地时间。这是“自大纪元以来的第二个”POSIX定义

  • 两者:time.time()不需要同步系统时钟,因此它可以反映其值(尽管它与本地时区无关)。不同的计算机可能同时获得不同的结果。另一方面,如果您的计算机时间同步的,那么很容易从时间戳中获取UTC时间(如果我们忽略leap秒):

    from datetime import datetime
    
    utc_dt = datetime.utcfromtimestamp(timestamp)

有关如何从各种Python版本的UTC时间获取时间戳的信息,请参见如何根据UTC将日期转换为自纪元以来的秒数?

The answer could be neither or both.

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

On how to get timestamps from UTC time in various Python versions, see How can I get a date converted to seconds since epoch according to UTC?


回答 4

我最终选择了:

>>> import time
>>> time.mktime(time.gmtime())
1509467455.0

I eventually settled for:

>>> import time
>>> time.mktime(time.gmtime())
1509467455.0

回答 5

在特定的时区没有“时代”这样的东西。纪元已明确定义为特定时间,因此,如果您更改时区,则时间本身也会改变。具体来说,这次是Jan 1 1970 00:00:00 UTC。因此time.time()返回自纪元以来的秒数。

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.


回答 6

时间戳始终是utc中的时间,但是当您调用datetime.datetime.fromtimestamp 它时,它会返回与该时间戳相对应的本地时区中的时间,因此结果取决于您的语言环境。

>>> import time, datetime

>>> time.time()
1564494136.0434234

>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)

存在arrow具有不同行为的漂亮的库。在相同情况下,它会返回带有UTC时区的时间对象。

>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>

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.

>>> import time, datetime

>>> time.time()
1564494136.0434234

>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)

There exist nice library arrow with different behaviour. In same case it returns you time object with UTC timezone.

>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>

获取当前时间(以毫秒为单位)在Python中?

问题:获取当前时间(以毫秒为单位)在Python中?

如何在Python中获取以毫秒为单位的当前时间?

How can I get the current time in milliseconds in Python?


回答 0

根据我上面的@samplebias的评论,这是我需要做的:

import time
millis = int(round(time.time() * 1000))
print millis

快点 谢谢大家,为您的大脑屁感到抱歉。

要重用:

import time

current_milli_time = lambda: int(round(time.time() * 1000))

然后:

>>> current_milli_time()
1378761833768

For what I needed, here’s what I did, based on @samplebias’ comment above:

import time
millis = int(round(time.time() * 1000))
print millis

Quick’n’easy. Thanks all, sorry for the brain fart.

For reuse:

import time

current_milli_time = lambda: int(round(time.time() * 1000))

Then:

>>> current_milli_time()
1378761833768

回答 1

time.time()可能只提供秒的分辨率,毫秒的首选方法是datetime

from datetime import datetime
dt = datetime.now()
dt.microsecond

time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime.

from datetime import datetime
dt = datetime.now()
dt.microsecond

回答 2

def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) 
def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) 

回答 3

3.7版开始,您可以time.time_ns()用来获取从纪元开始经过的纳秒级的时间。所以你可以做

ms = time.time_ns() // 1000000 

以毫秒为单位获取时间作为整数。

From version 3.7 you can use time.time_ns() to get time as passed nano seconds from epoch. So you can do

ms = time.time_ns() // 1000000 

to get time in mili-seconds as integer.


回答 4

只是示例代码:

import time
timestamp = int(time.time()*1000.0)

输出:1534343781311

Just sample code:

import time
timestamp = int(time.time()*1000.0)

Output: 1534343781311


回答 5

另一个解决方案是可以嵌入到自己的utils.py中的函数

import time as time_ #make sure we don't override time
def millis():
    return int(round(time_.time() * 1000))

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

回答 7

我发现以毫秒为单位获取当前UTC时间的最简单方法是:

# timeutil.py
import datetime


def get_epochtime_ms():
    return round(datetime.datetime.utcnow().timestamp() * 1000)

# sample.py
import timeutil


timeutil.get_epochtime_ms()

The simpliest way I’ve found to get the current UTC time in milliseconds is:

# timeutil.py
import datetime


def get_epochtime_ms():
    return round(datetime.datetime.utcnow().timestamp() * 1000)

# sample.py
import timeutil


timeutil.get_epochtime_ms()

回答 8

如果您担心测量经过的时间,则应使用单调时钟(python 3)。该时钟不受系统时钟更新的影响,例如,您会看到NTP查询是否调整了系统时间。

>>> import time
>>> millis = round(time.monotonic() * 1000)

它提供了以秒为单位的参考时间,可用于以后进行比较以测量经过的时间。

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.


回答 9

如果您使用我的代码(如下所示),则时间将以秒为单位,然后在十进制后为毫秒。我认为Windows和Unix之间有区别-如果有区别,请发表评论。

from time import time

x = time()
print(x)

我的结果(在Windows上)是:

1576095264.2682993

编辑:没有区别:)谢谢tc0nn

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.

from time import time

x = time()
print(x)

my result (on Windows) was:

1576095264.2682993

EDIT: There is no difference:) Thanks tc0nn


回答 10

这些乘以1000毫秒的乘法对于解决或使某些先决条件可接受可能是不错的选择。它可以用来填补数据库中实际上从未使用过的空白。虽然,对于需要精确定时的实际情况,它最终会失败。我不建议任何人将这种方法用于需要执行操作或在特定时间进行处理的关键任务操作。

例如:在美国,双向ping是30-80毫秒…您不能将其四舍五入并有效地使用它。

我自己的示例要求每秒执行一次任务,这意味着如果我在响应第一个任务后将其四舍五入,仍然会导致处理时间乘以每个主循环周期。最终每60秒调用一次函数。每天大约是1440 ..不太准确。

对于那些希望寻求更准确推理而不是解决从未真正使用过数据库缺口的人们来说,这只是一个想法。

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.


回答 11

这是使用datetime适用于Python 3 的模块的另一种解决方案。

datetime.datetime.timestamp(datetime.datetime.now())

Just another solution using the datetime module for Python 3.

datetime.datetime.timestamp(datetime.datetime.now())

Python的time.clock()与time.time()的准确性?

问题:Python的time.clock()与time.time()的准确性?

在Python中使用哪个计时更好?time.clock()或time.time()?哪一个提供更高的准确性?

例如:

start = time.clock()
... do something
elapsed = (time.clock() - start)

start = time.time()
... do something
elapsed = (time.time() - start)

Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?

for example:

start = time.clock()
... do something
elapsed = (time.clock() - start)

vs.

start = time.time()
... do something
elapsed = (time.time() - start)

回答 0

作为3.3,time.clock()已被弃用,并且它建议使用time.process_time()time.perf_counter()来代替。

于2.7,根据时间模块docs

time.clock()

在Unix上,以秒为单位返回当前处理器时间,以浮点数表示。精度(实际上是“处理器时间”的含义的确切定义)取决于同名C函数的精度,但是无论如何,这是用于基准化Python或计时算法的函数。

在Windows上,此函数将基于Win32函数QueryPerformanceCounter()返回自第一次调用此函数以来经过的时间(以秒为单位)的浮点数。分辨率通常优于一微秒。

此外,还有用于对代码段进行基准测试的timeit模块。

As of 3.3, time.clock() is deprecated, and it’s suggested to use time.process_time() or time.perf_counter() instead.

Previously in 2.7, according to the time module docs:

time.clock()

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.


回答 1

简短的答案是:大多数时候time.clock()会更好。但是,如果您要定时一些硬件(例如,您将某些算法放入GPU中),time.clock()则将摆脱这一时间,这time.time()是剩下的唯一解决方案。

注意:无论使用哪种方法,计时都将取决于您无法控制的因素(流程何时切换,多久……),这种情况会更糟,time.time()但也存在time.clock(),因此您永远不应只运行一次计时测试,但始终进行一系列测试,并查看时间的均值/方差。

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.


回答 2

其他人回答了:time.time()vs time.clock()

但是,如果出于基准测试/性能分析的目的而安排执行代码块的时间,则应查看timeit模块

Others have answered re: time.time() vs. time.clock().

However, if you’re timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the timeit module.


回答 3

要记住的一件事:更改系统时间会影响time.time()但不会影响time.clock()

我需要控制一些自动测试的执行。如果测试用例的一个步骤花费的时间超过给定的时间,则该TC将被中止以继续下一个步骤。

但有时需要更改系统时间(以检查被测应用程序的调度程序模块),因此在将来设置系统时间几小时后,TC超时到期并且测试用例被中止。我不得不从切换time.time()time.clock()正确处理此问题。

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.


回答 4

clock() ->浮点数

返回自进程开始或首次调用以来的CPU时间或实时时间clock()。这与系统记录一样精确。

time() ->浮点数

以秒为单位返回当前时间。如果系统时钟提供了小数秒,则可能会出现。

通常time()更精确,因为操作系统不会以存储系统时间(即实际时间)的精度来存储进程运行时间

clock() -> floating point number

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)


回答 5

取决于您所关心的。如果您指的是WALL TIME(例如,墙上的时钟上的时间),则time.clock()无法提供准确性,因为它可以管理CPU时间。

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.


回答 6

time()具有比clock()Linux 更好的精度。clock()仅具有小于10毫秒的精度。同时time()给出完美的精度。我的测试是在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

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

回答 7

区别是特定于平台的。

例如,Windows上的clock()与Linux上的时钟有很大不同。

对于您描述的示例种类,您可能需要“ timeit”模块。

The difference is very platform-specific.

clock() is very different on Windows than on Linux, for example.

For the sort of examples you describe, you probably want the “timeit” module instead.


回答 8

正如其他人指出time.clock()赞成不赞成 time.perf_counter()time.process_time(),但是Python 3.7引入了纳秒分辨率,定时time.perf_counter_ns()time.process_time_ns()time.time_ns(),连同其他3种功能。

PEP 564中详细介绍了这6个新的纳秒分辨率功能:

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

这些函数类似于不带_ns后缀的版本,但是作为Python int返回几纳秒。

正如其他人也指出的那样,使用该timeit模块来计时功能和小的代码片段。

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.


回答 9

在Unix上,time.clock()测量当前进程已使用的CPU时间量,因此,它对于测量过去某个时间点的经过时间没有好处。在Windows上,它将测量自第一次调用该功能以来经过的时钟秒数。在任何一个系统上,time.time()将返回自纪元以来经过的秒数。

如果您正在编写仅适用于Windows的代码,则两者都可以使用(尽管您将以不同的方式使用两者-time.clock()不需要减法)。如果这将要在Unix系统上运行,或者您想要保证可移植的代码,则需要使用time.time()。

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


回答 10

简短的答案:使用time.clock()在Python中计时。

在* nix系统上,clock()以浮点数形式返回处理器时间,以秒为单位。在Windows上,它以浮点数的形式返回自第一次调用此函数以来经过的秒数。

time()以毫秒为单位返回自纪元以来的秒数(以浮点数表示)。不能保证您会获得1秒钟更好的精度(即使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.


回答 11

据我所知,time.clock()具有您的系统所允许的精度。

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=0

for i in range(1,100):
    counter_time += t_time()

    for i in range(1,100):
        counter_clock += t_clock()

print "time() =",counter_time/100
print "clock() =",counter_clock/100

输出:

time()= 0.0993799996376

时钟()= 0.0993572257367

I use this code to compare 2 methods .My OS is windows 8 , processor core 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=0

for i in range(1,100):
    counter_time += t_time()

    for i in range(1,100):
        counter_clock += t_clock()

print "time() =",counter_time/100
print "clock() =",counter_clock/100

output:

time() = 0.0993799996376

clock() = 0.0993572257367


回答 13

正确答案:它们都是分数的相同长度。

但其速度更快,如果subjecttime

一些测试用例

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

我不是在瑞士的实验室工作,但已经过测试。

基于这样一个问题:time.clock()是不是更好time.time()

编辑:time.clock()是内部计数器,因此max 32BIT FLOAT如果不存储第一个/最后一个值,则不能在外部使用,受到限制,不能继续计数。无法合并另一个计数器…

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…


回答 14

time.clock()在Python 3.8中被删除,因为它具有平台相关的行为

  • Unix上,以秒为单位返回当前处理器时间,以浮点数表示。
  • Windows上,此函数返回自第一次调用此函数以来经过的挂钟秒数,作为浮点数

    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

那么选择哪个功能呢?

  • 处理器时间:这是该特定进程在CPU上主动执行所花费的时间。睡眠,等待Web请求或仅执行其他进程的时间不会对此有所帮助。

    • 采用 time.process_time()
  • 墙上时钟时间:这指的是“挂在墙上的时钟上”经过了多少时间,即不是实时时间。

    • 采用 time.perf_counter()

      • time.time() 还可以测量挂钟时间,但可以重置,因此您可以返回到过去
      • time.monotonic() 无法重置(单调=仅前进),但精度低于 time.perf_counter()

time.clock() was removed in Python 3.8 because it had platform-dependent behavior:

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

回答 15

比较Ubuntu Linux和Windows 7的测试结果。

在Ubuntu上

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5005500316619873

在Windows 7上

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5

Comparing test result between Ubuntu Linux and Windows 7.

On Ubuntu

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5005500316619873

On Windows 7

>>> start = time.time(); time.sleep(0.5); (time.time() - start)
0.5

我如何获得执行Python程序的时间?

问题:我如何获得执行Python程序的时间?

我在Python中有一个命令行程序,需要花一些时间才能完成。我想知道完成跑步所需的确切时间。

我看过该timeit模块,但似乎仅适用于少量代码段。我想安排整个节目的时间。

I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I’ve looked at the timeit module, but it seems it’s only for small snippets of code. I want to time the whole program.


回答 0

Python中最简单的方法:

import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))

假设您的程序至少需要十分之一秒才能运行。

印刷品:

--- 0.764891862869 seconds ---

The simplest way in Python:

import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))

This assumes that your program takes at least a tenth of second to run.

Prints:

--- 0.764891862869 seconds ---

回答 1

我将此timing.py模块放入自己的site-packages目录中,然后将其插入import timing模块顶部:

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

timing.log如果要显示的程序中有重要的阶段,我也可以从程序中调用。但仅包括即可import timing打印开始时间和结束时间以及总体经过时间。(请原谅我晦涩的secondsToStr功能,它只是将秒的浮点数格式设置为hh:mm:ss.sss形式。)

注意:以上代码的Python 3版本可以在此处此处找到。

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.


回答 2

在Linux或Unix中:

$ time python yourprogram.py

在Windows中,请参见以下StackOverflow问题: 如何在Windows命令行上测量命令的执行时间?

要获得更详细的输出,

$ 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

In Linux or Unix:

$ time python yourprogram.py

In Windows, see this StackOverflow question: How do I measure execution time of a command on the Windows command line?

For more verbose output,

$ 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

回答 3

我真的很喜欢Paul McGuire的答案,但是我使用Python3。因此,对于那些感兴趣的人:这是他的答案的一种修改,可用于* nix上的Python 3(我想在Windows下,clock()应该使用代替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")

如果您认为此方法有用,则仍应投票赞成他的答案,而不是像他所做的大部分工作一样;)。

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()返回处理器时间,这使我们只能计算该进程使用的时间(无论如何在Unix上)。该文档说“无论如何,这是用于基准化Python或计时算法的功能”

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”


回答 5

我喜欢输出 datetime模块提供,其中时间增量对象根据需要以人类可读的方式显示天,小时,分钟等。

例如:

from datetime import datetime
start_time = datetime.now()
# do your work here
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))

样品输出,例如

Duration: 0:00:08.309267

要么

Duration: 1 day, 1:51:24.269711

正如JF Sebastian提到的那样,这种方法在本地时间可能会遇到一些棘手的情况,因此使用起来更安全:

import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=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))

回答 6

您可以使用Python探查器cProfile来测量CPU时间,还可以测量每个函数内部花费了多少时间以及每个函数被调用了多少次。如果您想在不知道从哪里开始的情况下提高脚本性能,这将非常有用。另一个Stack Overflow问题的答案非常好。看看文档总是很高兴也。

这是一个示例,如何从命令行使用cProfile来分析脚本:

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

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:

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

回答 7

对于Linux甚至更好: time

$ 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

Even better for Linux: time

$ 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

回答 8

time.clock()

从版本3.3开始不推荐使用:此功能的行为取决于平台:根据您的要求,使用perf_counter()process_time()来具有明确定义的行为。

time.perf_counter()

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟以测量较短的持续时间。它的确包含整个系统的睡眠时间。

time.process_time()

返回当前进程的系统和用户CPU时间之和的值(以秒为单位)。它包括睡眠期间经过的时间。

start = time.process_time()
... do something
elapsed = (time.process_time() - start)

time.clock()

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.

start = time.process_time()
... do something
elapsed = (time.process_time() - start)

回答 9

只需使用该timeit模块。它同时适用于Python 2和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

它以秒为单位返回,您可以拥有执行时间。很简单,但是您应该将它们写在开始程序执行的主函数中。如果即使在遇到错误时也想获得执行时间,则将参数“开始”添加到该位置并进行计算,例如:

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

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)    

The following snippet prints elapsed time in a nice human readable <HH:MM:SS> format.

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)    

回答 11

from time import time
start_time = time()
...
end_time = time()
time_taken = end_time - start_time # time_taken is in seconds
hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)
from time import time
start_time = time()
...
end_time = time()
time_taken = end_time - start_time # time_taken is in seconds
hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)

回答 12

IPython中,“ timeit”任何脚本:

def foo():
    %run bar.py
timeit foo()

In IPython, “timeit” any script:

def foo():
    %run bar.py
timeit foo()

回答 13

我已经看过timeit模块,但似乎只适用于小段代码。我想安排整个节目的时间。

$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"

它运行一次your_module.main()功能,并使用以下命令打印经过的时间time.time()功能作为计时器。

/usr/bin/time在Python中进行仿真,请参见带有/ usr / bin / time的Python子进程:如何捕获计时信息,但忽略所有其他输出?

要测量time.sleep()每个函数的CPU时间(例如,不包括中的时间),您可以使用profile模块(cProfile在Python 2上):

$ python3 -mprofile your_module.py

如果您想使用相同的计时器,则可以传递-ptimeit上面的命令profile模块使用的。

请参阅如何配置Python脚本?

I’ve looked at the timeit module, but it seems it’s only for small snippets of code. I want to time the whole program.

$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"

It runs your_module.main() function one time and print the elapsed time using time.time() function as a timer.

To emulate /usr/bin/time in Python see Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?.

To measure CPU time (e.g., don’t include time during time.sleep()) for each function, you could use profile module (cProfile on Python 2):

$ python3 -mprofile your_module.py

You could pass -p to timeit command above if you want to use the same timer as profile module uses.

See How can you profile a Python script?


回答 14

我也喜欢Paul McGuire的答案,并提出了一个更适合我需求的上下文管理器表格。

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

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

回答 15

对于使用Jupyter Notebook的数据人员

在单元格中,可以使用Jupyter的%%timemagic命令来测量执行时间:

%%time
[ x**2 for x in range(10000)]

输出量

CPU times: user 4.54 ms, sys: 0 ns, total: 4.54 ms
Wall time: 4.12 ms

这只会捕获特定单元的执行时间。如果您想捕获整个笔记本(即程序)的执行时间,则可以在同一目录中创建一个新笔记本,然后在新笔记本中执行所有单元:

假设上面的笔记本名为example_notebook.ipynb。在同一目录中的新笔记本中:

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

For the data folks using Jupyter Notebook

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.

回答 16

有一个timeit模块可用于计时Python代码的执行时间。

它在Python文档26.6中提供了详细的文档和示例timeit —测量小代码段的执行时间

There is a timeit module which can be used to time the execution times of Python code.

It has detailed documentation and examples in Python documentation, 26.6. timeit — Measure execution time of small code snippets.


回答 17

使用line_profiler

line_profiler将分析各个代码行执行所需的时间。剖析器通过Cython在C中实现,以减少分析的开销。

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

结果将是:

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

Use line_profiler.

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

回答 18

我使用了一个非常简单的函数来计时部分代码执行时间:

import time
def timing():
    start_time = time.time()
    return lambda x: print("[{:.2f}s] {}".format(time.time() - start_time, x))

要使用它,只需在代码之前调用它以进行测量以检索函数计时,然后在代码后调用带有注释的函数。时间将显示在评论的前面。例如:

t = timing()
train = pd.read_csv('train.csv',
                        dtype={
                            'id': str,
                            'vendor_id': str,
                            'pickup_datetime': str,
                            'dropoff_datetime': str,
                            'passenger_count': int,
                            'pickup_longitude': np.float64,
                            'pickup_latitude': np.float64,
                            'dropoff_longitude': np.float64,
                            'dropoff_latitude': np.float64,
                            'store_and_fwd_flag': str,
                            'trip_duration': int,
                        },
                        parse_dates = ['pickup_datetime', 'dropoff_datetime'],
                   )
t("Loaded {} rows data from 'train'".format(len(train)))

然后输出将如下所示:

[9.35s] Loaded 1458644 rows data from 'train'

I used a very simple function to time a part of code execution:

import time
def timing():
    start_time = time.time()
    return lambda x: print("[{:.2f}s] {}".format(time.time() - start_time, x))

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:

t = timing()
train = pd.read_csv('train.csv',
                        dtype={
                            'id': str,
                            'vendor_id': str,
                            'pickup_datetime': str,
                            'dropoff_datetime': str,
                            'passenger_count': int,
                            'pickup_longitude': np.float64,
                            'pickup_latitude': np.float64,
                            'dropoff_longitude': np.float64,
                            'dropoff_latitude': np.float64,
                            'store_and_fwd_flag': str,
                            'trip_duration': int,
                        },
                        parse_dates = ['pickup_datetime', 'dropoff_datetime'],
                   )
t("Loaded {} rows data from 'train'".format(len(train)))

Then the output will look like this:

[9.35s] Loaded 1458644 rows data from 'train'

回答 19

我在很多地方都遇到过同样的问题,所以我创建了一个便利包horology。您可以安装它,pip install horology然后以一种优雅的方式完成它:

from horology import Timing

with Timing(name='Important calculations: '):
    prepare()
    do_your_stuff()
    finish_sth()

将输出:

Important calculations: 12.43 ms

甚至更简单(如果您有一个功能):

from horology import timed

@timed
def main():
    ...

将输出:

main: 7.12 h

它照顾单位和舍入。它适用于python 3.6或更高版本。

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.


回答 20

这是Paul McGuire的答案,对我有用。以防万一有人在运行那个困难。

import atexit
from time import clock

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

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)

def endlog():
    end = clock()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(clock())

def main():
    start = clock()
    atexit.register(endlog)
    log("Start Program")

timing.main()导入文件后,从程序中调用。

This is Paul McGuire’s answer that works for me. Just in case someone was having trouble running that one.

import atexit
from time import clock

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

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)

def endlog():
    end = clock()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(clock())

def main():
    start = clock()
    atexit.register(endlog)
    log("Start Program")

Call timing.main() from your program after importing the file.


回答 21

Timeit是Python中的一个类,用于计算小代码块的执行时间。

Default_timer是此类中的一种方法,用于测量挂钟计时,而不是CPU执行时间。因此,其他进程执行可能会对此产生干扰。因此,这对于较小的代码块很有用。

代码示例如下:

from timeit import default_timer as timer

start= timer()

# Some logic

end = timer()

print("Time taken:", end-start)

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)

回答 22

稍后的答案,但我使用timeit

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

  • 在内包装所有代码,包括您可能拥有的任何导入code_to_test
  • number 参数指定代码应重复的次数。
  • 演示版

Later answer, but I use timeit:

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

回答 23

Python程序执行时间的时间可能不一致,具体取决于:

  • 可以使用不同的算法评估同一程序
  • 运行时间因算法而异
  • 运行时间因实现而异
  • 运行时间因计算机而异
  • 基于少量输入,运行时间是不可预测的

这是因为最有效的方法是使用“增长顺序”并学习“ O”表示法来正确执行。

无论如何,您可以尝试使用以下简单算法以特定的机器每秒计数步骤来评估任何Python程序的性能: 使其适应您要评估的程序

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

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)

You do this simply in Python. There is no need to make it complicated.

import time

start = time.localtime()
end = time.localtime()
"""Total execution time in seconds$ """
print(end.tm_sec - start.tm_sec)

回答 25

与@rogeriopvl的响应类似,我添加了一点修改,以使用相同的库将长时间运行的作业转换为时分秒。

import time
start_time = time.time()
main()
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))

样本输出

Time Taken: 00:00:08

Similar to the response from @rogeriopvl I added a slight modification to convert to hour minute seconds using the same library for long running jobs.

import time
start_time = time.time()
main()
seconds = time.time() - start_time
print('Time Taken:', time.strftime("%H:%M:%S",time.gmtime(seconds)))

Sample Output

Time Taken: 00:00:08

回答 26

首先,通过以管理员身份打开命令提示符(CMD)并在其中键入命令,以安装对人类友好的软件包- pip install humanfriendly

码:

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

Output:


回答 27

要使用metakermit更新的Python 2.7 答案,您将需要单调包。

代码如下:

from datetime import timedelta
from monotonic import monotonic

start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))

To use metakermit’s updated answer for Python 2.7, you will require the monotonic package.

The code would then be as follows:

from datetime import timedelta
from monotonic import monotonic

start_time = monotonic()
end_time = monotonic()
print(timedelta(seconds=end_time - start_time))

回答 28

我尝试使用以下脚本找到时差。

import time

start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")

I tried and found time difference using the following scripts.

import time

start_time = time.perf_counter()
[main code here]
print (time.perf_counter() - start_time, "seconds")

回答 29

如果要以微秒为单位测量时间,则可以使用以下版本,完全基于Paul McGuireNicojo的回答-这是Python 3代码。我还添加了一些颜色:

import atexit
from time import time
from datetime import timedelta, datetime


def seconds_to_str(elapsed=None):
    if elapsed is None:
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    else:
        return str(timedelta(seconds=elapsed))


def log(txt, elapsed=None):
    colour_cyan = '\033[36m'
    colour_reset = '\033[0;0;39m'
    colour_red = '\033[31m'
    print('\n ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
    if elapsed:
        print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)


def end_log():
    end = time()
    elapsed = end-start
    log("End Program", seconds_to_str(elapsed))


start = time()
atexit.register(end_log)
log("Start Program")

log()=>函数,输出定时信息。

txt ==>要记录的第一个参数,以及用来标记时间的字符串。

atexit ==> Python模块,用于注册程序退出时可以调用的函数。

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:

import atexit
from time import time
from datetime import timedelta, datetime


def seconds_to_str(elapsed=None):
    if elapsed is None:
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    else:
        return str(timedelta(seconds=elapsed))


def log(txt, elapsed=None):
    colour_cyan = '\033[36m'
    colour_reset = '\033[0;0;39m'
    colour_red = '\033[31m'
    print('\n ' + colour_cyan + '  [TIMING]> [' + seconds_to_str() + '] ----> ' + txt + '\n' + colour_reset)
    if elapsed:
        print("\n " + colour_red + " [TIMING]> Elapsed time ==> " + elapsed + "\n" + colour_reset)


def end_log():
    end = time()
    elapsed = end-start
    log("End Program", seconds_to_str(elapsed))


start = time()
atexit.register(end_log)
log("Start Program")

log() => function that prints out the timing information.

txt ==> first argument to log, and its string to mark timing.

atexit ==> Python module to register functions that you can call when the program exits.


如何在Python中获取当前时间

问题:如何在Python中获取当前时间

获取当前时间的模块/方法是什么?

What is the module/method used to get the current time?


回答 0

采用:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)

>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150

而只是时间:

>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)

>>> print(datetime.datetime.now().time())
15:08:24.789150

请参阅文档以获取更多信息。

要保存输入,可以datetimedatetime模块中导入对象:

>>> from datetime import datetime

然后datetime.从以上所有位置移除引线。

Use:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)

>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150

And just the time:

>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)

>>> print(datetime.datetime.now().time())
15:08:24.789150

See the documentation for more information.

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime

Then remove the leading datetime. from all of the above.


回答 1

您可以使用time.strftime()

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

You can use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

回答 2

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

对于此示例,输出将如下所示: '2013-09-18 11:16:32'

这是strftime指令列表。

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

For this example, the output will be like this: '2013-09-18 11:16:32'

Here is the list of strftime directives.


回答 3

Harley的答案相似,但使用该str()函数可得到快速n脏的,人类可读的格式:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

Similar to Harley’s answer, but use the str() function for a quick-n-dirty, slightly more human readable format:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

回答 4

如何使用Python获取当前时间?

time模块

time模块提供的功能可以告诉我们时间(自纪元以来的秒数)以及其他实用程序。

import time

Unix时代时间

这是保存数据库时应使用的时间戳格式。它是一个简单的浮点数,可以转换为整数。这对于以秒为单位的算术也很有用,因为它代表自1970年1月1日00:00:00以来的秒数,并且相对于我们接下来要看的其他时间表示,它是记忆光。

>>> time.time()
1424233311.771502

该时间戳记不占leap秒,因此不是线性的-leap秒将被忽略。因此,尽管它不等同于国际UTC标准,但它很接近,因此对于大多数记录保存情况而言,这是相当好的。

但是,这对于人工调度而言并不理想。如果您希望在某个特定时间发生将来的事件,则需要使用可以解析为datetime对象或序列化datetime对象的字符串存储该时间(稍后将对此进行描述)。

time.ctime

您还可以用操作系统首选的方式来表示当前时间(这意味着当您更改系统首选项时,它可以更改,因此请不要像其他人所期望的那样,将其作为所有系统的标准时间) 。这通常是用户友好的,但通常不会导致字符串可以按时间顺序排序:

>>> time.ctime()
'Tue Feb 17 23:21:56 2015'

您还可以通过以下方式将时间戳混合为易于阅读的形式ctime

>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'

这种转换也不利于保存记录(除非只能由人类解析的文本,并且随着光学字符识别和人工智能的改进,我认为这些案件的数量将会减少)。

datetime 模组

datetime模块在这里也非常有用:

>>> import datetime

datetime.datetime.now

datetime.now是一类方法,它返回当前时间。它使用time.localtime不带时区信息的(如果未提供,否则请参阅下面的了解时区)。它具有在外壳上回显的表示形式(允许您重新创建等效的对象),但是在打印(或强制转换为str)时,它具有人类可读(和几乎ISO)的格式,而词典编排相当于按时间顺序排序:

>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461

日期时间 utcnow

通过执行以下操作,您可以获取全球标准UTC时间中的datetime对象:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

UTC是几乎等同于GMT时区的时间标准。(虽然GMT和UTC的夏令时不变,但他们的用户可能会在夏季切换到其他时区,例如英国夏令时。)

datetime时区感知

但是,到目前为止,我们创建的datetime对象都无法轻松转换为各种时区。我们可以使用以下pytz模块解决该问题:

>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)

等效地,在Python 3中,我们有一个timezone带有utc timezone实例的类,它也使对象知道时区(但在没有方便的pytz模块的情况下,转换成另一个时区留给读者练习):

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

而且我们看到我们可以轻松地从原始utc对象转换为时区。

>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00

您还可以使用pytztimezone localize方法或通过替换tzinfo属性(使用replace,这是盲目的完成)来使朴素的datetime对象知道的,但是这些方法比最佳实践更多的是不得已而为之:

>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)

pytz模块使我们能够使datetime对象知道时区,并将时间转换为pytz模块中可用的数百个时区。

人们可以表面上连载这个对象UTC时间和存储在数据库中,但它需要远远更多的内存和比简单地存储Unix纪元的时间,这是我第一次表现出更容易出错。

其他查看时间的方式更容易出错,尤其是在处理可能来自不同时区的数据时。您希望不要将字符串或序列化日期时间对象用于哪个时区。

如果您正在使用Python为用户显示时间,则ctime可以很好地工作,而不是在表中(通常排序不佳),而是在时钟中。但是,我个人建议在Python中使用Unix时间或时区感知UTC datetime对象处理时间时。

How do I get the current time in Python?

The time module

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:

>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461

datetime’s utcnow

You can get a datetime object in UTC time, a global standard, by doing this:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

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

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

And we see we can easily convert to timezones from the original utc object.

>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00

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:

>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)

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.


回答 5

from time import time

t = time()
  • t -浮点数,适用于时间间隔测量。

Unix和Windows平台有所不同。

Do

from time import time

t = time()
  • t – float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.


回答 6

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

以指定格式输出当前GMT。还有一种localtime()方法。

页面有更多详细信息。

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

That outputs the current GMT in the specified format. There is also a localtime() method.

This page has more details.


回答 7

先前的答案都是不错的建议,但我发现它最容易使用ctime()

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

这样可以很好地格式化当前本地时间的字符串表示形式。

The previous answers are all good suggestions, but I find it easiest to use ctime():

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

This gives a nicely formatted string representation of the current local time.


回答 8

最快的方法是:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

The quickest way is:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

回答 9

如果您需要当前时间作为time对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

If you need current time as a time object:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

回答 10

.isoformat() 在文档中,但尚未在此处(这与@Ray Vega的答案非常相似):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

.isoformat() is in the documentation, but not yet here (this is mighty similar to @Ray Vega’s answer):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

回答 11

为什么不问美国海军的官方计时器美国海军天文台呢?

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…


回答 12

使用熊猫来获取当前时间,有点过头了:

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)

输出:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

Using pandas to get the current time, kind of overkilling the problem at hand:

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)

Output:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

回答 13

这就是我最终要进行的工作:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

此外,该表是选择适当的格式代码得到格式化只是你想要的方式日期(从Python的“日期时间”的文档的必要参考这里)。

This is what I ended up going with:

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


回答 14

如果您已经在使用numpy,则可以直接使用numpy.datetime64()函数。

import numpy as np
str(np.datetime64('now'))

仅限日期:

str(np.datetime64('today'))

或者,如果您已经在使用熊猫,则可以使用pandas.to_datetime()函数

import pandas as pd
str(pd.to_datetime('now'))

要么,

str(pd.to_datetime('today'))

if you are using numpy already then directly you can use numpy.datetime64() function.

import numpy as np
str(np.datetime64('now'))

for only date:

str(np.datetime64('today'))

or, if you are using pandas already then you can use pandas.to_datetime() function

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))

回答 15

您可以使用以下time模块:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

资本的使用Y给出了全年,而使用则y给出了06/02/15

您还可以使用以下代码来延长时间:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

You can use the time module:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

The use of the capital Y gives the full year, and using y would give 06/02/15.

You could also use the following code to give a more lengthy time:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

回答 16

datetime.now()返回当前时间作为朴素的datetime对象,该对象表示本地时区中的时间。该值可能不明确,例如在DST转换期间(“回退”)。为避免歧义,应使用UTC时区:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

或具有附加时区信息的时区感知对象(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

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:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

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 time

print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond

dir(date)或任何变量,包括包装。您可以获得与该变量关联的所有属性和方法。

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'
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'

回答 19

默认情况下,now()函数以YYYY-MM-DD HH:MM:SS:MS格式返回输出。使用以下示例脚本在Python脚本中获取当前日期和时间,并在屏幕上打印结果。创建getDateTime1.py具有以下内容的文件。

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

输出如下所示:

2018-03-01 17:03:46.759624

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.

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624

回答 20

这个问题并不需要仅仅为了它而提供一个新的答案……但是,一个闪亮的新玩具/模块就足够了。那就是Pendulum库,它似乎可以完成arrow尝试的各种工作,但没有固有的缺陷和bug困扰着arrow。

例如,原始问题的答案:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

有很多需要解决的标准,包括多个RFC和ISO。曾经把它们混在一起;不用担心,请看一看dir(pendulum.constants)。不过,这里还有RFC和ISO格式。

当我们说本地的时候,虽然是什么意思?好吧,我的意思是:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

大概大多数人都在别的地方。

继续下去。长话短说:Pendulum尝试在日期和时间上执行HTTP请求的操作。值得考虑,尤其是它的易用性和广泛的文档资料。

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:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

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:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

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.


回答 21

时区的当前时间

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones
pytz.all_timezones

Current time of a timezone

from datetime import datetime
import pytz

tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))

tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones
pytz.all_timezones

回答 22

试用http://crsmithdev.com/arrow/中的箭头模块:

import arrow
arrow.now()

或UTC版本:

arrow.utcnow()

要更改其输出,请添加.format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

对于特定时区:

arrow.now('US/Pacific')

一小时前:

arrow.utcnow().replace(hours=-1)

或者,如果您要要旨。

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'

Try the arrow module from http://crsmithdev.com/arrow/:

import arrow
arrow.now()

Or the UTC version:

arrow.utcnow()

To change its output, add .format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

For a specific timezone:

arrow.now('US/Pacific')

An hour ago:

arrow.utcnow().replace(hours=-1)

Or if you want the gist.

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

但是我只想毫秒,对不对?获得它们的最短方法:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

从上一个乘法中添加或删除零以调整小数点位数,或者仅:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

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:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

回答 24

您可以使用此功能获取时间(不幸的是,它没有显示AM或PM):

def gettime():
    from datetime import datetime
    return ((str(datetime.now())).split(' ')[1]).split('.')[0]

要获取以后合并的小时,分​​钟,秒和毫秒,可以使用以下功能:

小时:

def gethour():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]

分钟:

def getminute():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]

第二:

def getsecond():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]

毫秒:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]

You can use this function to get the time (unfortunately it doesn’t say AM or PM):

def gettime():
    from datetime import datetime
    return ((str(datetime.now())).split(' ')[1]).split('.')[0]

To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:

Hour:

def gethour():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]

Minute:

def getminute():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]

Second:

def getsecond():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]

Millisecond:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]

回答 25

如果只需要当前时间戳(以毫秒为单位)(例如,测量执行时间),则也可以使用“ timeit”模块:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

If you just want the current timestamp in ms (for example, to measure execution time), you can also use the “timeit” module:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

回答 26

以下是我用来获取时间而不必进行格式化的内容。有些人不喜欢split方法,但是在这里很有用:

from time import ctime
print ctime().split()[3]

它将以HH:MM:SS格式打印。

The following is what I use to get the time without having to format. Some people don’t like the split method, but it is useful here:

from time import ctime
print ctime().split()[3]

It will print in HH:MM:SS format.


回答 27

因为还没有人提及它,所以我最近遇到了这个问题……pytz时区的fromutc()方法与datetime的utcnow()结合是我发现获得有用的当前时间(和日期)的最佳方法在任何时区。

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

如果您想要的只是时间,那么您可以使用local_time.time()

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.

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

If all you want is the time, you can then get that with local_time.time().


回答 28

这个问题是针对Python的,但是由于Django是Python使用最广泛的框架之一,因此必须注意,如果您使用的是Django,则可以始终使用timezone.now()而不是datetime.datetime.now()。前者是时区“知道”的,而后者则不是。

请参阅此SO答案Django文档,以获取详细信息和背后的原理timezone.now()

from django.utils import timezone

now = timezone.now()

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.

See this SO answer and the Django doc for details and rationale behind timezone.now().

from django.utils import timezone

now = timezone.now()

回答 29

您可以使用ctime()来做到这一点:

from time import time, ctime
t = time()
ctime(t)

输出:

Sat Sep 14 21:27:08 2019

这些输出是不同的,因为返回的时间戳ctime()取决于您的地理位置。

You can do so using ctime():

from time import time, ctime
t = time()
ctime(t)

output:

Sat Sep 14 21:27:08 2019

These outputs are different because the timestamp returned by ctime() depends on your geographical location.