Search code examples
loggingpython-2to3

Python 2 code not working with Python 3 can't solve


i'm upgrading an old python 2 program and have been having so much trouble upgrading the code and everything but i've been able to get by thanks to the docs, but i can't figure this one out.

Its a very simple function but i keep getting weird errors i never got in python2, here is the code:

def log(self, message):
    print("[SYSTEM][{0}]".format(datetime.strftime(time.gmtime()+message, "%Y-%m-%d %H:%M:%S")))

Now the error i get is this:

TypeError: can only concatenate tuple (not "str") to tuple

Here is how it should look outputted to the console:

[SYSTEM][2020-06-04 17:30:51]MessageHere

Any help would be appreciated as this has been driving me nuts.


Solution

  • Fixing your original method:

    def log(self, message):
        print("[SYSTEM][{0}]".format(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')) + message)
    

    A bit cleaner version using f-strings:

    def log(self, message):
        print(f"[SYSTEM][{datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')}]{message}")