antwilson1720
antwilson1720

Reputation: 330

How to update a timestamp?

I'm trying to set up a log file as such for a discord bot. I am using Python for the bot and the issue I am having is related to the time module.

My code:

import time

currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

After a command is posted in the discord it runs:

print(str(currentTime) + " - Emoji's requested!")

Everything is printed to the console with the correct date and time the first run. However, the next time it prints the same date and time as before, even if the next post is two days later.

Upvotes: 0

Views: 2122

Answers (2)

g.d.d.c
g.d.d.c

Reputation: 47988

I mean ... you stored the value that came from the call to time.localtime(). That value is static at the time that you call that method. You could instead replace it with a function, like this:

def currentTime():
  return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

And then change your print line to:

print(str(currentTime()) + " - Emoji's requested!")

Upvotes: 1

Tim Woocker
Tim Woocker

Reputation: 1996

You are calling time.localtime() only once. You need to call it everytime you want to have the current time. If you don't call it again, it will just use the old time.

So call

currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

everytime before you try to print that time.

You could make a simple method to make it shorter each time like this:

def get_time() -> str:
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

and then print messages like this: print(get_time() + " - Emoji's requested!")

Upvotes: 1

Related Questions