time.time()和datetime.datetime.now()在描述符

时间:2017-12-01 08:04:11

标签: python

在Python中编码时,获取当前时间的常用方法是time.time()datetime.datetime.now()。但在此代码之前我从未怀疑过他们的结果:

import time

class A(object):
    def __get__(self, instance, owner):
        print '__get__ is run'
        return time.time()
    def __set__(self, instance, value):
        print('let me set, but i will not', value)

class C(object):
    a = A()

c1 = C()
c2 = C()
print(c1.a)
c1.a = time.time()
print(c1.a)
print('-' * 20)
print(c2.a)

此代码的结果是:

__get__ is run
1512115138.19
('let me set, but i will not', 1512115138.188)
__get__ is run
1512115138.19
--------------------
__get__ is run
1512115138.19
[Finished in 0.2s]

地球上发生了什么?为什么这三个time.time()调用会得到相同的结果? datetime.datetime.now()的结果相同。在python 2和python 3中也有相同的结果。 我无法找到一些python技术来解释它。

1 个答案:

答案 0 :(得分:2)

实际上,这是一个关于精度的问题,请查看link。您可以看到更精确的输出:

__get__ is run
1512115904.6300762
let me set, but i will not 1512115904.631677
__get__ is run
1512115904.6346197
--------------------
__get__ is run
1512115904.6372328