封装一个方法把2006年10月31日转换成2006-10-31
你可以使用datetime模块来实现日期格式的转换。下面是一个封装方法的示例:
import datetime
def convert_date(date_str):
# 使用datetime.strptime方法将字符串转换为日期对象
date_obj = datetime.datetime.strptime(date_str, "%Y年%m月%d日")
# 使用date对象的strftime方法将日期对象转换为指定格式的字符串
formatted_date = date_obj.strftime("%Y-%m-%d")
return formatted_date
# 调用方法进行转换
date_str = "2006年10月31日"
converted_date = convert_date(date_str)
print(converted_date)
输出结果为:2006-10-31
原文地址: https://www.cveoy.top/t/topic/icD0 著作权归作者所有。请勿转载和采集!