尝试将我的由铁砧制成的计时器应用更改为显示HH:MM:SS而不是几秒钟
“ self.label_time_elapsed.text =” {}“。format( (datetime.now()-self.start_time).strftime('%H:%M:%S')) )”-我问过另一个问题,现在尝试了另一个错误
from anvil import *
import anvil.server
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
from datetime import datetime
class Form1(Form1Template):
def __init__(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
# Any code you write here will run when the form opens.
self.start_time = None
def button_start_click(self, **event_args):
"""This method is called when the button is clicked"""
self.start_time = datetime.now()
self.button_start.visible = False
self.button_stop.visible = True
def button_stop_click(self, **event_args):
"""This method is called when the button is clicked"""
self.stop_time = datetime.now()
self.total_time = self.stop_time - self.start_time
anvil.server.call('add_session', self.start_time,
self.total_time.seconds)
self.start_time = None
self.button_start.visible = True
self.button_stop.visible = False
def timer_progress_tick(self, **event_args):
"""This method is called Every [interval] seconds. Does not trigger
if [interval] is 0."""
if self.start_time is not None:
self.label_time_elapsed.text = "{}".format(
(datetime.now() - self.start_time).strptime('%H:%M:%S'))
AttributeError:“ timedelta”对象没有属性“ strptime” 在Form1的第38行
答案 0 :(得分:0)
timedelta
对象包含两个日期之间的差额-2年,2毫秒等。
您试图将这个timedelta强制转换为日期/时间的字符串表示形式;片刻,这是不可能的。
now - self.start_time
不是日期或时间,而是从现在到现在之间经过的时间。用秒表示,而不是:
(datetime.now() - self.start_time).total_seconds()
编辑:要将这些秒转换为HH:MM:SS
:
td = datetime.now() - self.start_time
minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
self.label_time_elapsed.text = '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
答案 1 :(得分:0)
您可以尝试使用自定义功能。
例如:
import datetime
def cust(seconds):
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "{hour}:{min}:{sec}".format(hour=int(h), min=int(m), sec=int(s))
now = datetime.datetime.now()
d = (now - datetime.datetime.strptime("2016-01-01", "%Y-%m-%d")).total_seconds()
print(cust(d))
输出:
30349:52:12
以您的情况
cust(datetime.now() - self.start_time).total_seconds())