日期格式转换报错:将%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
相关产品推荐
相关产品推荐

