Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you update variable in Class each time?

I am trying to code a Class, which upon calling, for example: print(TimeNow.time_now) would print current time (but it’s not realtime), as in, each time I call it, it doesn’t return updated value.

If I tried this every time, it would make my code long, so I am trying to code it in a Class so that I can easily call it wherever I want to print time:

time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(time_now)

Full code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import datetime

command = ""

class TimeNow:
     time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

while command != "quit":
    command = input("-> ").lower()

    if command == "1":
    
         print(TimeNow.time_now)

>Solution :

This is not a good case for a class definition. A simple function will work:

def time_now():
     return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

print(time_now())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading