-2

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:

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)
Cassano
  • 253
  • 5
  • 36

2 Answers2

1

This method should work for what you want, but requires making an instance of TimeNow

import datetime

command = ""

class TimeNow:
    @property
    def time_now(self): 
        return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

instance = TimeNow()
    
while command != "quit":
    command = input("-> ").lower()
    if command == "1":
    
         print(instance.time_now)
1

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())
Paul Cornelius
  • 9,245
  • 1
  • 15
  • 24