string 转日期string 转日期
要将一个字符串转换为日期,需要使用日期时间格式化函数。具体的转换过程可以根据字符串的格式来进行处理。以下是一个示例代码,将字符串"2021-01-01"转换为日期类型:
import datetime
date_string = "2021-01-01"
date_format = "%Y-%m-%d"
date = datetime.datetime.strptime(date_string, date_format).date()
print(date)
输出结果为:
2021-01-01
在上述代码中,strptime()函数将字符串按照指定的日期格式解析为一个datetime对象,然后通过.date()方法获取日期部分。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/i1qx 著作权归作者所有。请勿转载和采集!