日期格式转换代码部分测试用例失败问题排查
日期格式转换问题排查
我正在解决将“Day Month Year”格式的日期字符串转换为YYYY-MM-DD格式的问题,要求如下:
- 输入日期中,Day是带后缀的数字(如1st、2nd),Month是三位缩写(如Jan、Feb),Year范围在[1900,2100]
- 输出需为4位年份、2位月份、2位日期的YYYY-MM-DD格式
部分测试用例能正常通过,比如输入“20th Oct 2052”时输出正确的2052-10-20,但输入“26th May 1960”时输出1960-5-26,正确结果应为1960-05-26,以下是我的代码:
class Solution(object): def reformatDate(self, date): list_date = date.split() YYYY = "" MM = "" DD = "" DD_dict = { "1st": "1", "2nd": "2", "3rd": "3", "4th": "4", "5th": "5", "6th": "6", "7th": "7", "8th": "8", "9th": "9", "10th": "10", "11th": "11", "12th": "12", "13th": "13", "14th": "14", "15th": "15", "16th": "16", "17th": "17", "18th": "18", "19th": "19", "20th": "20", "21st": "21", "22nd": "22", "23rd": "23", "24th": "24", "25th": "25", "26th": "26", "27th": "27", "28th": "28", "29th": "29", "30th": "30", "31st": "31" } MM_dict = { "Jan": "1", "Feb": "2", "Mar": "3", "Apr": "4", "May": "5", "Jun": "6", "Jul": "7", "Aug": "8", "Sep": "9", "Oct": "10", "Nov": "11", "Dec": "12" } for char in list_date: if char in DD_dict: if int(DD_dict[char]) < 10: DD += '0' + DD_dict[char] else: DD += DD_dict[char] elif char in MM_dict: if int(MM_dict[char]) < 10: MM += '0' + MM_dict[char] else: MM += MM_dict[char] else: YYYY += char return "".join(f'{int(YYYY)}-{int(MM)}-{int(DD)}') if __name__ == '__main__': date = "20th Oct 2052" d2 = "26th May 1960" print(Solution().reformatDate(date)) print(Solution().reformatDate(d2))
错误原因分析
问题出在最后的返回语句:
return "".join(f'{int(YYYY)}-{int(MM)}-{int(DD)}')
- 你已经在前面的逻辑中为月份和日期补了前导零(比如May对应的MM会被处理成"05"),但这里将
MM和DD转换为整数时,前导零会被自动移除,导致输出变成5而非05 - 另外,
"".join()在这里完全多余,因为f-string本身已经是完整的字符串
修复方案
直接返回拼接好的字符串,不需要转换为整数:
return f'{YYYY}-{MM}-{DD}'
可选优化方案
可以提前在字典中存储带前导零的字符串,省去判断补零的逻辑,让代码更简洁:
DD_dict = { "1st": "01", "2nd": "02", "3rd": "03", "4th": "04", "5th": "05", "6th": "06", "7th": "07", "8th": "08", "9th": "09", "10th": "10", "11th": "11", "12th": "12", "13th": "13", "14th": "14", "15th": "15", "16th": "16", "17th": "17", "18th": "18", "19th": "19", "20th": "20", "21st": "21", "22nd": "22", "23rd": "23", "24th": "24", "25th": "25", "26th": "26", "27th": "27", "28th": "28", "29th": "29", "30th": "30", "31st": "31" } MM_dict = { "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12" }
之后处理逻辑可以简化为:
for char in list_date: if char in DD_dict: DD = DD_dict[char] elif char in MM_dict: MM = MM_dict[char] else: YYYY = char
内容的提问来源于stack exchange,提问作者klaus19
相关产品推荐
相关产品推荐

