前言本次总结一下Python时间的相关操作。如果你的业务不使用与时间相关的操作,你的业务基本上永远不会使用它们。但是一旦你的业务使用了时间操作,你就会发现,哦,时间操作无处不在。..所以想了想,还是总结一下吧。这一次,我们将使用类型注释的方法。时间包importtimetimestamp是从1970年1月1日00:00:00标准时区诞生到现在的总秒数。代码timestamp=time.time()#type:floatprint(timestamp,type(timestamp))执行结果Sleep有时候我们可能需要模仿一些IO请求,假装让程序休眠一会儿,所以就需要使用sleep时间的函数。代码#Sleepfor1secondtime.sleep(1)本地时区本地时区需要使用时间的localtime方法。代码t=time.localtime()#type:time.struct_timeprint(t,type(t))执行结果localtime也可以接收一个时间戳参数。代码#将时间戳转换成struct_time对象t=time.localtime(1606395685.1878598)#type:time.struct_timeprint(t,type(t))执行结果简单时间格式代码t=time.ctime()#type:strprint(t,type(t))执行结果这样虽然可以显示时间,但是这种格式确实不太好看。同样,time.ctime()也可以接收时间戳。代码t=time.ctime(1606395685.1878598)#type:strprint(t,type(t))执行结果timeformatdateformat->string(strftime)代码t=time.localtime()#type:time.struct_timet_str=time.strftime("%Y-%m-%d",t)#type:strprint(t_str,type(t_str))执行结果字符串date->date(strptime)codet_str="2020-11-02"t_time=time.strptime(t_str,"%Y-%m-%d")#type:time.struct_timeprint(t_time,type(t_time))执行结果格式补充主要有如下格式详解:https://www.runoob.com/python/python-date-time.htmldatetime包注意:datetime和time是两种不同的类型,不能混用。fromdatetimeimportdatetimedatetime.today()代码t=datetime.today()#type:datetimeprint(t,type(t))print(t.year)#yearprint(t.month)#month执行结果datetime.now()和datetime.today()基本相同,返回当地时间。代码t=datetime.now()#type:datetimeprint(t,type(t))执行结果datetime.utcnow()utcnow返回标准(UTC)时间,以上两个返回本地时间,我们是东八区!代码t=datetime.now()print("Dongbadistricttime:",t)t=datetime.utcnow()#type:datetimeprint("UTCtime:",t)有时执行结果时间戳为datetime,得到什么是时间戳,所以我们只能传递它。代码#timestamptimestamp=time.time()print(f"timestamp:{timestamp},type:{type(timestamp)}")#timestamptodatetimet=datetime.fromtimestamp(timestamp)print(f"t:{t},type:{type(t)}")执行结果datetime->stringdate(strftime)codefromdatetimeimportdatetimet=datetime.now()str_datetime=t.strftime("%Y-%m-%d%H:%M:%S")print(f"stringdate:{str_datetime},type:{type(str_datetime)}")执行结果stringdate->datetime(strptime)codefromdatetimeimportdatetimestr_datetime="2020-11-2922:05:20"t=datetime.strptime(str_datetime,"%Y-%m-%d%H:%M:%S")print(f"t:{t},type:{type(t)}")时间加法和执行结果的减法是这次的重头戏。好像只有datetime包有时间加减。时间加减法有很多具体的用途。多久过期,多久提醒需要提前算好时间,这个还是很重要的。代码fromdatetimeimportdatetimeimportdatetimeasidatetimet=datetime.now()print(f"当前时间:{t}")three_day=t+idatetime.timedelta(days=3)print(f"三天后时间:{three_day}")执行结果可以发现,这次确实是+成功了。但是自带的时间加减法有问题。您只能添加几天,而不是几个月甚至几年。如果要时间+月份等,就得自己写逻辑了。有个免费加减datetime时间的包正好解决了这个问题。安装pipinstallpython-dateutilcodefromdatetimeimportdatetimefromdateutil.relativedeltaimportrelativedeltat=datetime.now()print(f"currenttime:{t}")three_time=t+relativedelta(months=3)print(f"timeinthreemonths:{three_time}")one_year=t+relativedelta(years=1)print(f"一年后:{one_year}")up_year=t+relativedelta(years=-1)print(f"去年这个时候:{up_year}")执行为结果,用法很简单。如果要加月/年,写正数,如果要减,写负数。这种方法基本上弥补了python在运行时间上的不足。总结这篇文章主要说一下Python时间的相关总结。相对来说,更推荐datetime。需要注意的是time和datetime是两种类型,不能混用。其实最主要的还是stringtime->time类型,在实践中用的比较多!对了,python-dateutil还有relativedelta相关的方法,可以自由加减时间,很方便。
