如何用Python基于字符串类型的年月日生成MMddyyyy格式日期?
解决Python生成MMddyyyy格式日期的问题
你现在的代码只完成了非空判断,没实现核心的格式转换逻辑,而且注释里的代码有两处问题:一是字符串模板没替换实际变量,二是strptime是用来把字符串解析成datetime对象的,不是生成指定格式字符串的工具。要生成MMddyyyy格式的日期字符串,有两种靠谱的修改方式:
方式一:用datetime模块(自带日期合法性校验)
这种方法会先验证输入的年、月、日是否合法(比如不会允许2月30日这种无效日期),再生成目标格式:
from datetime import datetime year = "2022" month = "7" day = "15" if year and month and day: # 空字符串在布尔判断里直接为False,比写len()更简洁 print('variables are not empty') try: # 把字符串转成datetime对象,同时校验日期合法性 date_obj = datetime(int(year), int(month), int(day)) # 生成MMddyyyy格式的字符串 formatted_date = date_obj.strftime("%m%d%Y") print(formatted_date) # 输出:07152022 except ValueError: print("输入的年、月、日不合法") else: print('variables are empty')
方式二:直接字符串格式化(高效,适合确定日期合法的场景)
如果能保证输入的年、月、日都是有效日期,直接用字符串补零格式化更简单:
year = "2022" month = "7" day = "15" if year and month and day: print('variables are not empty') # 用zfill(2)给月、日补零,确保是两位数字 formatted_date = f"{month.zfill(2)}{day.zfill(2)}{year}" print(formatted_date) # 输出:07152022 else: print('variables are empty')
关键说明
- 非空判断:
if year and month and day等价于原代码的长度判断,但写法更简洁。 - 补零处理:
zfill(2)会自动在短字符串前补零,把"7"变成"07",满足MM(两位月份)的要求。
内容的提问来源于stack exchange,提问作者Baba
相关产品推荐
相关产品推荐

