【问题标题】:Datetime seconds are not accurate日期时间秒数不准确
【发布时间】:2017-03-21 20:20:07
【问题描述】:

我正在尝试在正常打印之前打印当前时间

global begtime
begtime = str(datetime.datetime.now()).split('.')[0]
global secondtime
secondtime = begtime.split(' ')[1]
global time
time = '[' + secondtime + ']' + ':'
print time

datetime.datetime.now 返回格式为:

year.month.date hour.minute.second

所以我首先在 '.' 处拆分。得到单独的时间,然后我在空间分裂以获得时间。

然后我将其格式化为 [hour:min:sec]

它可以工作,但时间不正确,它会为所有打印件打印相同的时间,即使它们相隔几分钟。

我想要每次打印的准确时间。

【问题讨论】:

  • 使用全局变量是不好的做法

标签: python datetime


【解决方案1】:

对于您的代码,您可能在程序中设置了较早的时间,然后在稍后访问它时认为它正在生成一个新时间。每次打印时它都不会生成新的时间。每次运行begtime = str(datetime.datetime.now()).split('.')[0]时只会生成一个新时间@

更好的方法是使用Date.strftime(format)。我在下面提供了一个示例。

import datetime
import time

now = datetime.datetime.now()
print(now.strftime('[%I:%M:%S]'))

time.sleep(10)

now = datetime.datetime.now()
print(now.strftime('[%I:%M:%S]'))

这将打印当前时间,然后在当前时间 10 秒后打印 10 秒。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2020-01-05
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多