[英]Saving date and time in a variable
我想将创建类实例的“特定”时刻保存在变量中,如何在Python 3中做到这一点? 请看下面的代码片段:
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()
如果相反,您随后仅访问属性 ,而没有创建新的类实例,则会发现时间是固定的。
您的实例是在同一秒内创建的。 将time.sleep(1)
放在它们之间,您会看到时间的变化。 您也可以使用%X.%f
来打印时间的微秒,但是时钟的分辨率可能仍会使用相同的标记来创建它们。
解决此问题以确保您拥有唯一时间的一种方法是等待时间“打勾”:
import time
class Ants(object):
"""Workers"""
ID = 1
def __init__(self):
import datetime
self.borningTime = datetime.datetime.now()
# Wait for the time to change
while datetime.datetime.now() == self.borningTime:
pass
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.%f") # Add microseconds.
my1Ant = Ants()
my2Ant = Ants()
print(my1Ant.get_ID(), my1Ant.get_borningTime())
print(my2Ant.get_ID(), my2Ant.get_borningTime())
输出:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.