2

I am trying to do a time counter in python using QTime and show this time in a QLabel using PyQt. I need to do this, to show how many time has passed since my program started to work, using this format of time: 00:00:00. I read the docs of QTime and tried another code that I have searched for on the internet, but I can not make it work.

This is part of my code:

class MyApplication(QtGui.QApplication):
  def __init__(self, *args, **kwargs):
    super(MyApplication, self).__init__(*args, **kwargs)

    self.t = QTime()                      #I start QTime at the same time
    self.t.start()                        # the program starts.

    self.label_1 = QtGui.QLabel("Time since the program started:")

    self.time_label = QtGui.QLabel("00:00:00")

    self.tmr = QTimer()                   #I use QTimer because I need it 
                                          #for another part of the code
    self.tmr.timeout.connect(self.clock)

  def clock(self):
    self.m = 0
    self.elapsed = self.t.elapsed()

    self.s = int((self.elapsed)/1000)
    if self.s == 60:
        self.m += 1
        self.s = 0 

    self.time_sec = str(self.s)
    self.time_min = str(self.m)
    self.time = self.time_min + ":" + self.time_sec

    self.time_label.setText(self.time)     #I show the time in this QLabel()

When I build this, I get this format of time: 0:0 and after 60 seconds (it shows the seconds) I get this result: 1:0, and nothing else happens.

How can I make the time counter that I need with this format: 00:00:00. Can I do it using QTimer? Hope you can help me.

------ EDIT ------

Thanks to @amicitas and @linusg answer, I´ve tried the datetime module, and wrote this simple code:

class MyApplication(QtGui.QApplication):
  def __init__(self, *args, **kwargs):
    super(MyApplication, self).__init__(*args, **kwargs)

    self.t0 = datetime.now()

    self.tmr = QTimer()                   
    self.tmr.timeout.connect(self.clock)


  def.clock(self):
    self.t1 = datetime.now()

    self.hour = self.t1.hour - self.t0.hour
    self.minute = self.t1.minute - self.t0.minute
    self.second = self.t1.second - self.t0.second

    print self.hour, self.minute, self.second

But, when I build this, at the moment the counter reaches 45 seconds, it turns 45 to -15 and "1 minute" appears. This is:

When it reaches 0:0:44, it turns to 0:1:-15.

What could be the problem? And how can I show the time format that I need? This is 00:00:00. Hope you can help me.

Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54
Pablo Flores
  • 667
  • 1
  • 13
  • 33
  • 1
    If you really just want to show the user how long it has been since the program started, it would easier and more accurate to just use the standard python time routines (`datetime.datetime.now()`) to save the time that the program started, and then calculate the difference between the current time and the start time. A `QTimer()` is not guaranteed to be accurate for this kind of stopwatch functionality. – amicitas May 15 '16 at 14:30
  • As @amicitas has mentioned, a usage of `datetime` would be more easier! Would that be an option? – linusg May 15 '16 at 14:38
  • Thank you for your answers. Yes, it is a good option, but I do not know how to show the time format that I need with this module. – Pablo Flores May 15 '16 at 15:21
  • You don't want to subtract the individual hour/minute/second components, you want to subtract the whole time `self.t1 - self.t0` – Brendan Abel May 17 '16 at 01:44

2 Answers2

3

I have written and tested the following code for you:

from datetime import datetime
import time

if __name__== '__main__':

    initTimeObj = datetime.now()
    nullRef = datetime(initTimeObj.year, initTimeObj.month, initTimeObj.day, 0, 0, 0)

    print("Initial time:")
    print(str(initTimeObj.hour) + ':' + str(initTimeObj.minute) + ':' + str(initTimeObj.second))
    print("")


    while(True):
        time.sleep(1)
        myDiff = datetime.now() - initTimeObj
        myTimeObj = nullRef + myDiff

        print(str(myTimeObj.hour) + ':' + str(myTimeObj.minute) + ':' + str(myTimeObj.second))

        # Now you get a counting as follows:
        # 0:0:1
        # 0:0:2
        # 0:0:3
        # ...
        # 0:0:59
        # 0:1:0
        # 0:1:1
        # 0:1:2
        # ...

This code does exactly what you need. It starts counting from 0:0:0and continues doing so. Some more tweaks might be necessary if you really want to have a double-digit format, like 00:00:00. If you want, I can look into that further.

I hope this helped you out. Please let me know if it worked for you.

K.Mulier
  • 8,069
  • 15
  • 79
  • 141
  • Thank you for your answer. It helps me a lot. Thank you. I have a question altought: what does this line do? `nullRef = datetime(initTimeObj.year, initTimeObj.month, initTimeObj.day, 0, 0, 0)` – Pablo Flores May 17 '16 at 01:19
  • 1
    Hi Pablo. nullref is a datetime object, just like initTimeObj. It is equivalent to initTimeObj (same year, month and day), but it represents the very beginning of that day (00:00:00). So now you can easily add seconds (or minutes, or anything) to nullref. It will count up, just like what you need :-) – K.Mulier May 17 '16 at 04:46
  • Hi Pablo, I hope this helped you out. If you've got any further questions, don't hesitate to ask me. I'm happy to help :-) – K.Mulier May 17 '16 at 08:18
0
import datetime
import time

start = datetime.datetime.now()

while True:
    elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
    hour = int(elapsed_seconds // 3600)
    min = int(elapsed_seconds % 3600 // 60)
    seconds = int(elapsed_seconds % 60)
    print '{:02d}:{:02d}:{:02d}'.format(hour, minute, second)
    time.sleep(1)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118