Search code examples
pythonpython-datetime

How do I write the time from datetime to a file in Python?


I'm trying to have my Python code write everything it does to a log, with a timestamp. But it doesn't seem to work.

this is my current code:

filePath= Path('.')
time=datetime.datetime.now()
bot_log = ["","Set up the file path thingy"]
with open ('bot.log', 'a') as f:
  f.write('\n'.join(bot_log)%
  datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
  print(bot_log[0])

but when I run it it says:

Traceback (most recent call last):
  File "c:\Users\Name\Yuna-Discord-Bot\Yuna Discord Bot.py", line 15, in <module>
    f.write('\n'.join(bot_log)%
TypeError: not all arguments converted during string formatting

I have tried multiple things to fix it, and this is the latest one. is there something I'm doing wrong or missing? I also want the time to be in front of the log message, but I don't think it would do that (if it worked).


Solution

  • You need to put "%s" somewhere in the input string before string formatting. Here's more detailed explanation.

    Try this:

    filePath= Path('.')
    time=datetime.datetime.now()
    bot_log = "%s Set up the file path thingy\n"
    with open ('bot.log', 'a') as f:
      f.write(bot_log % datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
      print(bot_log)