Search code examples
pythonpython-datetimetimedelta

AttributeError: 'timedelta' object has no attribute 'strptime' at Form1, line 38


Trying to change my timer app made from anvil to display HH:MM:SS instead just seconds

"self.label_time_elapsed.text = "{}".format( (datetime.now() - self.start_time).strftime('%H:%M:%S')) )" - tried this from another question i asked, now i have a different bug

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' object has no attribute 'strptime' at Form1, line 38


Solution

  • timedelta objects contain the delta between two dates - 2 years, 2 milliseconds, etc.

    You're trying to coerce this timedelta into a string representation of a date / time; a moment in time, which isn't possible.

    now - self.start_time isn't a date or time, it's the amount of time elapsed between then and now. Express it as, say, seconds instead:

    (datetime.now() - self.start_time).total_seconds()

    edit: To convert those seconds into 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)