Python实现时间显示功能输出异常,该如何修复代码问题?
核心问题原因
- 日期格式不匹配:
time.strftime("%d")输出为带前导零的两位字符串(如1号输出"01"),与你定义的序数列表中的不带前导零的字符串无法匹配,导致日期判断永远走错误分支。 - 函数无返回值:
day()函数仅执行打印操作,没有返回值,因此拼接月份时会输出None。 - 分支逻辑错误:使用多个独立
if而非if-elif-else结构,就算前面的条件匹配成功,后续的分支判断依然会执行,最终触发末尾的错误提示分支。
修正后完整代码
import time local_time = time.localtime() # 转成整数再转字符串,去掉日期前导零 time_string_d = str(int(time.strftime("%d", local_time))) time_string_m = time.strftime("%m", local_time) time_string_hm = time.strftime("%H:%M", local_time) day_st = ['1', '21', '31'] day_nd = ['2', '22'] day_rd = ['3', '23'] # 用字典映射月份,减少冗余判断 month_map = { '1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June', '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December' } def get_day_suffix(): if time_string_d in day_st: return 'st' elif time_string_d in day_nd: return 'nd' elif time_string_d in day_rd: return 'rd' # 剩余合法日期默认都是th elif 1 <= int(time_string_d) <=31: return 'th' else: return 'There was an error in the day detecting system.' def show_time(): if time_string_m not in month_map: print('There was an error in the month detecting system.') return suffix = get_day_suffix() if 'error' in suffix: print(suffix) return print(f'It is {time_string_hm}') print(f'{month_map[time_string_m]} {time_string_d}{suffix}') # 调用函数输出结果 show_time()
效果说明
修正后会直接输出符合预期的格式,示例:
It is 14:20 October 8th
如果出现非法日期或月份,会单独输出对应的错误提示,不会生成多余内容。
内容的提问来源于stack exchange,提问作者Ákos Molnár
相关产品推荐
相关产品推荐

