参考网址
blog.csdn.net/weixin_4170…
简介
以上所有的功能,都需要使用datetime这个库包。
该库包下有很多的模块,及xxx.py文件。文件中有很多的类class,或者功能函数。
import datetime
<1>字符串类型-->日期时间类型
我们需要用到的是datetime库包中的datetime.py模块中的strptime()函数。
从函数名的字面上理解:strptime(): str-->post-->time
该函数需要传入2个参数,一个是字符串,一个是时间的格式。
import datetime
strTime = '2022-06-11 11:03'
strTime = datetime.datetime.strptime(strTime, "%Y-%m-%d %H:%M")
print(strTime)
2022-06-11 11:03:00
注意事项:
a, 日期时间转换时,读取的格式要和给定的格式一样,否则会因为无法匹配而报错
【格式1 和 格式2 需要保持一致】
b, 转换之后的日期格式会自动加上'秒'位

<2>时间类型-->字符串
根据自己的需求,通过strftime( )函数内的控制符把日期时间格式转换成不同的格式,内容参考:
import datetime
strTime = '2022-06-11 11:03'
strTime = datetime.datetime.strptime(strTime,"%Y-%m-%d %H:%M")
print(strTime)
strTimeFormat = strTime.strftime("%d-%b-%Y %H:%M %p")
print(strTimeFormat)
<3>日期时间往前推,往后推
日期时间之间的加减,要求所有参与的对象都必须是时间类型的,不能是字符串类型。
如果是字符串类型的,比如提前转换为时间类型的。
实现此功能,我们用到的是datetime中的timedelta()函数。
该函数提供了days,seconds,microseconds,milliseconds,minutes,hours,weeks等时间颗粒度的加减。
可以看到,以上这些都是复数。
import datetime
strTime = '2022-06-11 11:03'
strTime = datetime.datetime.strptime(strTime,"%Y-%m-%d %H:%M")
print(strTime)
strTimeFormat = strTime.strftime("%d-%b-%Y %H:%M %p")
print(strTimeFormat)
addDays= (strTime + datetime.timedelta(days=2)).strftime("%d-%b-%Y %H:%M %p")
print(addDays)
minusHours = (strTime + datetime.timedelta(hours=-12)).strftime("%d-%b-%Y %H:%M %p")
print(minusHours)
addMinutes = (strTime + datetime.timedelta(minutes=70)).strftime("%d-%b-%Y %H:%M %p")
print(addMinutes)

<4>时间的加减
2个日期时间,必须是时间类型的,不能是字符串类型。
如果是字符串类型,先转换为时间类型。
(datetime.strptime(r["cancel_time"], time_format) -
datetime.strptime(r["create_time"],time_format)).seconds