在变量中保存日期和时间

2024-09-30 10:42:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把创建一个的实例的“特定”时刻保存在一个变量中,在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())

当我运行这个时,输出是:

^{pr2}$

当我再次运行它时:

Ant ID:00001 2018-05-24  17:43:05
Ant ID:00002 2018-05-24  17:43:05

这意味着“自我。出生时间“在我第一次创建实例时没有记录和保留它的值(这是我想要的),每次调用它都会得到一个新值。在

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

敬上。在


Tags: 实例代码selfidgetdatetimereturndef
2条回答

您的实例将在同一秒钟内创建。{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())

输出:

^{pr2}$

在我的系统上,大约需要15毫秒才能得到一个新的时间值。在

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

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

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

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

my1Ant = Ants()
my2Ant = Ants()

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

相关问题 更多 >

    热门问题