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

Time:11-28

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).

CodePudding user response:

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"]
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])

CodePudding user response:

It looks like you want to write three strings to your file as separate lines. I've rearranged your code to create a single list to pass to writelines, which expects an iterable:

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

EDIT: From the comments the desire is to prepend the timestamp to the message and keep it on the same line. I've used f-strings as I prefer the clarity they provide:

import datetime
from pathlib import Path

filePath = Path('.')

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

You could also look at the logging module which does a lot of this for you.

CodePudding user response:

Not all your string formatters are correct, try something like this:

datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S")

Hope you can work off of this.

Good Luck!

  • Related