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

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

我制作了这个脚本来跟踪我的当前时间和当前电池百分比(然后将其附加到剪贴板以便我可以将其粘贴到某个地方):

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

我想这样输出"Hours:Minutes battery percentage" = "12:25 PM 94%"

问题是,如果我这样写代码:

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

...我会得到一个 ValueError:strftime 格式以原始 % 结尾(不知道为什么)

但是如果这样写:

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

...我不会得到任何错误,但问题是,它看起来 weird(小时部分只是字母 "I")。即使我将它粘贴到某处,它也会像这样“95%I:25 PM”(应该是“95% 12:25 PM”)

您只需要处理 datetime.strftime(...) 之外的字符串连接。例如:

from datetime import datetime

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