1. 字符串转成时间
使用datetime.strptime
from datetime import datetime
start_date = "2023-11-28"
start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
print('start_date',start_date)
print('start_datetime',start_datetime)
print('type(start_datetime)',type(start_datetime))
输出结果
start_date 2023-11-28
start_datetime 2023-11-28 00:00:00
type(start_datetime) <class 'datetime.datetime'>
2. 时间转字符串
使用datetime.strftime('%Y-%m-%d')
str_time = start_datetime.strftime('%Y-%m-%d')
print('str_time',str_time)
print('type(str_time)',type(str_time))
输出
str_time 2023-11-28
type(str_time) <class 'str'>