python :字符串类型和时间类型之间的转换,时间的加减法

265 阅读2分钟

参考网址

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, 转换之后的日期格式会自动加上'秒'位

图片.png

<2>时间类型-->字符串

 根据自己的需求,通过strftime( )函数内的控制符把日期时间格式转换成不同的格式,内容参考:
    # 需要把一个 '2022-06-11 11:03' 转换成  '11-Jun-2022 11:03 AM ',可以通过下面方式实现:

    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)

# 加2天
addDays= (strTime + datetime.timedelta(days=2)).strftime("%d-%b-%Y %H:%M %p") 
print(addDays)

# 减12个小时
minusHours = (strTime + datetime.timedelta(hours=-12)).strftime("%d-%b-%Y %H:%M %p") #减12个小时
print(minusHours)

# 加70分钟
addMinutes = (strTime + datetime.timedelta(minutes=70)).strftime("%d-%b-%Y %H:%M %p") #加70分钟
print(addMinutes)

图片.png

<4>时间的加减

  2个日期时间,必须是时间类型的,不能是字符串类型。
  如果是字符串类型,先转换为时间类型。
# 得到2个日期之间的秒数
# 前者>后者才有意义
(datetime.strptime(r["cancel_time"], time_format) - 
datetime.strptime(r["create_time"],time_format)).seconds