You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

日期格式转换报错:将%d/%m/%Y转为%-d-%b-%Y时触发ValueError

解决strftime格式转换报错问题

错误原因

问题出在%-d格式符上:它是POSIX系统(Linux/macOS)专属的语法,用于去除日期数字前的前导零(比如将05转为5),但Windows系统的strftime不支持该写法,因此触发ValueError: Invalid format string。


方案1:跨平台兼容写法

通过判断当前操作系统,匹配对应格式符:

from datetime import datetime
import sys
from tkinter import *
from tkcalendar import DateEntry

win = Tk()
win.geometry("750x250")
win.title("Example")

def convert():
    date1 = cal.get()
    datetimeobject = datetime.strptime(date1, '%d/%m/%Y')
    print(date1)
    # 根据系统选择对应格式符
    if sys.platform.startswith('win'):
        new_format = datetimeobject.strftime('%#d-%b-%Y')
    else:
        new_format = datetimeobject.strftime('%-d-%b-%Y')
    print(new_format)

cal = DateEntry(win, width=16, background="gray61", foreground="white", bd=2, date_pattern='dd/mm/y')
cal.pack(pady=20)

btn = Button(win, command=convert, text='PRESS')
btn.pack(pady=50)

win.mainloop()

方案2:字符串处理去除前导零(无需判断系统)

先生成带前导零的格式字符串,再手动去除日期部分的前导零:

from datetime import datetime
from tkinter import *
from tkcalendar import DateEntry

win = Tk()
win.geometry("750x250")
win.title("Example")

def convert():
    date1 = cal.get()
    datetimeobject = datetime.strptime(date1, '%d/%m/%Y')
    print(date1)
    # 先生成带前导零的格式,拆分后处理日期部分
    temp_format = datetimeobject.strftime('%d-%b-%Y')
    day, rest = temp_format.split('-', 1)
    new_format = f"{int(day)}-{rest}"
    print(new_format)

cal = DateEntry(win, width=16, background="gray61", foreground="white", bd=2, date_pattern='dd/mm/y')
cal.pack(pady=20)

btn = Button(win, command=convert, text='PRESS')
btn.pack(pady=50)

win.mainloop()

内容的提问来源于stack exchange,提问作者Nemanja Gavranovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:30:26