Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在变量中保存日期和时间_Python_Python 3.x_Class_Python Datetime - Fatal编程技术网

Python 在变量中保存日期和时间

Python 在变量中保存日期和时间,python,python-3.x,class,python-datetime,Python,Python 3.x,Class,Python Datetime,我想将创建类实例的“特定”时刻保存在一个变量中,在Python3中如何做到这一点?请查看以下截取的代码: class Ants(object): """Workers""" ID = 1 def __init__(self): import datetime self.borningTime = datetime.datetime.now() self.ID = Ants.ID Ants.ID += 1

我想将创建类实例的“特定”时刻保存在一个变量中,在Python3中如何做到这一点?请查看以下截取的代码:

class Ants(object):
    """Workers"""
    ID = 1
    def __init__(self):
        import datetime
        self.borningTime = datetime.datetime.now()
        self.ID = Ants.ID
        Ants.ID += 1

    def get_ID(self):
        return "Ant ID:" + str(self.ID).zfill(5)

    def get_borningTime(self):
        return self.borningTime.strftime("%Y-%m-%d  %X")

my1Ant = Ants()
my2Ant = Ants()

print(my1Ant.get_ID(), my1Ant.get_borningTime())
print(my2Ant.get_ID(), my2Ant.get_borningTime())
运行此操作时,输出为:

Ant ID:00001 2018-05-24  17:42:45
Ant ID:00002 2018-05-24  17:42:45
当我再次运行它时:

Ant ID:00001 2018-05-24  17:43:05
Ant ID:00002 2018-05-24  17:43:05
这意味着“self.borningTime”在我第一次创建实例时(这就是我想要的)并没有记录和保留它的值,而是每次调用它时都会得到一个新的值

我怎么能做我想做的?我的代码中缺少了什么?提前谢谢


注意。

每次创建类实例时都会记录时间

每次运行脚本时都会更新时间的原因是您正在通过以下两行创建新实例:

my1Ant = Ants()
my2Ant = Ants()

如果您随后只访问属性,而不创建新的类实例,则会发现时间是固定的。

您的实例是在同一秒内创建的。在它们之间放置一个
时间。睡眠(1)
,你会看到时间的变化。您也可以使用
%X.%f
打印时间的微秒数,但时钟的分辨率可能仍然会使用相同的戳记创建它们

解决此问题的一种方法是确保您有唯一的时间,即等待时间“勾选”:

输出:

Ant ID:00001 2018-05-24  09:10:41.085253
Ant ID:00002 2018-05-24  09:10:41.100867
在我的系统上,获得新的时间值大约需要15毫秒

如果不需要日期/时间值,
time.perf_counter()
的精度要高得多,但与特定的日期和时间无关。您只能比较两个读数之间的差异。在我的系统中,每滴答声不到一微秒,但你仍然可以称之为快到不滴答声:

>>> time.perf_counter() - time.perf_counter()
0.0
>>> time.perf_counter() - time.perf_counter()
-3.775817631890277e-07
>>> time.perf_counter() - time.perf_counter()
0.0
>>> time.perf_counter() - time.perf_counter()
-3.775817631890277e-07