Python Forum

Full Version: How to print the current time in color
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I want to create a variable, and when I print that variable, it needs to be in a certain color. This is my current code

import datetime
from colored import fg, attr


current_time = datetime.datetime.now().strftime('%H:%M:%S') % (fg(151), attr(0))
print(current_time)
Error:
Traceback (most recent call last): File "C:/Users/Julius/PycharmProjects/Fenix/venv/Grosbasket script.py", line 8, in <module> current_time = datetime.datetime.now().strftime('%H:%M:%S') % (fg(151), attr(0)) TypeError: not all arguments converted during string formatting
How do I solve this error?
This works for me on python3.8
import timedate
from colored import fg
current_time = datetime.datetime.now().strftime('%H:%M:%S')
print(fg(11),current_time)
You're just using the bare string created by strftime(). You created a format string (with the %) and gave it the attributes, but it couldn't find a "%s" or similar to insert the data.

You just need concatenate those attributes, either in the print itself, or create a new string with them inside and print the new string.

One method
data_to_print = "Hello there" #could be your datetime
print(fg(151), data_to_print, attr(0))
(Apr-15-2020, 09:13 PM)bowlofred Wrote: [ -> ]You're just using the bare string created by strftime(). You created a format string (with the %) and gave it the attributes, but it couldn't find a "%s" or similar to insert the data.

You just need concatenate those attributes, either in the print itself, or create a new string with them inside and print the new string.

One method
data_to_print = "Hello there" #could be your datetime
print(fg(151), data_to_print, attr(0))
cool thanks!