Search code examples
pythondatetimestrftime

I get a ValueError: strftime format ends with raw % for root.clipboard_append(d.strftime("%I:%M %p" + percent+"%"))


I made this script to track my current time and current battery percentage (and then append it to clipboard so I can paste it somewhere):

from tkinter import *
from urllib import parse
from tkinter import Tk
import tkinter.ttk as ttk
from datetime import datetime
import psutil


root = Tk() 
root.title("Current Time")
root.geometry('250x57+1000+103')

lbl = Label(root, text="Time")
lbl.pack()

def clicked():

    d = datetime.now()
    print(d.strftime("%I:%M"))

    battery = psutil.sensors_battery()
    plugged = battery.power_plugged
    percent = str(battery.percent)
    print(percent+'%')


    root.clipboard_clear()
    root.clipboard_append(d.strftime(percent+"%" + "%I:%M %p"))
    lbl.configure(text= d.strftime(percent+"%" + "%I:%M %p"))

style = ttk.Style(root)
style.theme_use('clam')
style.configure('TButton', bordercolor="black")

btn = ttk.Button(root, text='Show Current Time', style='TButton', command=clicked, width = 37)
btn.pack()

root.wm_attributes("-topmost", 1)
root.mainloop()

I want to output it like this "Hours:Minutes battery percentage" = "12:25 PM 94%"

problem is, if I write the code like this:

root.clipboard_append(d.strftime("%I:%M %p" + percent+"%"))
lbl.configure(text= d.strftime("%I:%M %p" + percent+"%"))

... I'm gonna get a ValueError: strftime format ends with raw % (not sure why)

But if it's written like this:

root.clipboard_append(d.strftime(percent+"%" "%I:%M %p"))
lbl.configure(text= d.strftime(percent+"%" "%I:%M %p"))

... I'm not gonna get any error, but the problem is, it looks weird (the hour part will just be letter "I"). And even if I paste it somewhere, it will be like this "95%I:25 PM" (it should be "95% 12:25 PM")


Solution

  • You just need to handle the string concatenation outside datetime.strftime(...). For example:

    from datetime import datetime
    
    p = 95
    d = datetime.now()
    s = '{} {}%'.format(d.strftime('%I:%M %p'), p)
    print(s)
    # OUTPUT
    # 05:02 AM 95%