Python学习之time模块的基本使用
前言
在我们学习的过程中,肯定会用到各种各样的模块。所以今天我们从time模块开始学习
首先我们在使用某个模块的时候,肯定要先导入这个模块
importtime
而当我们想看看这个模块是干什么的,我们可以使用help函数来看
print(help(time))#打印帮助信息
"E:\ProgramFiles(x86)\python_3.8\python.exe"D:/Application/pycharm_works/_1/test/python模块之time模块.py Helponbuilt-inmoduletime: NAME time-Thismoduleprovidesvariousfunctionstomanipulatetimevalues. DESCRIPTION Therearetwostandardrepresentationsoftime.Oneisthenumber ofsecondssincetheEpoch,inUTC(a.k.a.GMT).Itmaybeaninteger orafloatingpointnumber(torepresentfractionsofseconds). TheEpochissystem-defined;onUnix,itisgenerallyJanuary1st,1970. Theactualvaluecanberetrievedbycallinggmtime(0). Theotherrepresentationisatupleof9integersgivinglocaltime. Thetupleitemsare: year(includingcentury,e.g.1998) month(1-12) day(1-31) hours(0-23) minutes(0-59) seconds(0-59) weekday(0-6,Mondayis0) Julianday(dayintheyear,1-366) DST(DaylightSavingsTime)flag(-1,0or1) IftheDSTflagis0,thetimeisgivenintheregulartimezone; ifitis1,thetimeisgivenintheDSTtimezone; ifitis-1,mktime()shouldguessbasedonthedateandtime. CLASSES builtins.tuple(builtins.object) struct_time classstruct_time(builtins.tuple) |struct_time(iterable=(),/) | |Thetimevalueasreturnedbygmtime(),localtime(),andstrptime(),and |acceptedbyasctime(),mktime()andstrftime().Maybeconsideredasa |sequenceof9integers. | |Notethatseveralfields'valuesarenotthesameasthosedefinedby |theClanguagestandardforstructtm.Forexample,thevalueofthe |fieldtm_yearistheactualyear,notyear-1900.Seeindividual |fields'descriptionsfordetails. | |Methodresolutionorder: |struct_time |builtins.tuple |builtins.object | |Methodsdefinedhere: | |__reduce__(...) |Helperforpickle. | |__repr__(self,/) |Returnrepr(self). | |---------------------------------------------------------------------- |Staticmethodsdefinedhere: | |__new__(*args,**kwargs)frombuiltins.type |Createandreturnanewobject.Seehelp(type)foraccuratesignature. | |---------------------------------------------------------------------- |Datadescriptorsdefinedhere: | |tm_gmtoff |offsetfromUTCinseconds | |tm_hour |hours,range[0,23] | |tm_isdst |1ifsummertimeisineffect,0ifnot,and-1ifunknown | |tm_mday |dayofmonth,range[1,31] | |tm_min |minutes,range[0,59] | |tm_mon |monthofyear,range[1,12] | |tm_sec |seconds,range[0,61]) | |tm_wday |dayofweek,range[0,6],Mondayis0 | |tm_yday |dayofyear,range[1,366] | |tm_year |year,forexample,1993 | |tm_zone |abbreviationoftimezonename | |---------------------------------------------------------------------- |Dataandotherattributesdefinedhere: | |n_fields=11 | |n_sequence_fields=9 | |n_unnamed_fields=0 | |---------------------------------------------------------------------- |Methodsinheritedfrombuiltins.tuple: | |__add__(self,value,/) |Returnself+value. | |__contains__(self,key,/) |Returnkeyinself. | |__eq__(self,value,/) |Returnself==value. | |__ge__(self,value,/) |Returnself>=value. | |__getattribute__(self,name,/) |Returngetattr(self,name). | |__getitem__(self,key,/) |Returnself[key]. | |__getnewargs__(self,/) | |__gt__(self,value,/) |Returnself>value. | |__hash__(self,/) |Returnhash(self). | |__iter__(self,/) |Implementiter(self). | |__le__(self,value,/) |Returnself<=value. | |__len__(self,/) |Returnlen(self). | |__lt__(self,value,/) |Returnselfstring Convertatimetupletoastring,e.g.'SatJun0616:26:111998'. Whenthetimetupleisnotpresent,currenttimeasreturnedbylocaltime() isused. ctime(...) ctime(seconds)->string ConvertatimeinsecondssincetheEpochtoastringinlocaltime. Thisisequivalenttoasctime(localtime(seconds)).Whenthetimetupleis notpresent,currenttimeasreturnedbylocaltime()isused. get_clock_info(...) get_clock_info(name:str)->dict Getinformationofthespecifiedclock. gmtime(...) gmtime([seconds])->(tm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst) ConvertsecondssincetheEpochtoatimetupleexpressingUTC(a.k.a. GMT).When'seconds'isnotpassedin,convertthecurrenttimeinstead. Iftheplatformsupportsthetm_gmtoffandtm_zone,theyareavailableas attributesonly. localtime(...) localtime([seconds])->(tm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst) ConvertsecondssincetheEpochtoatimetupleexpressinglocaltime. When'seconds'isnotpassedin,convertthecurrenttimeinstead. mktime(...) mktime(tuple)->floatingpointnumber ConvertatimetupleinlocaltimetosecondssincetheEpoch. Notethatmktime(gmtime(0))willnotgenerallyreturnzeroformost timezones;insteadthereturnedvaluewilleitherbeequaltothat ofthetimezoneoraltzoneattributesonthetimemodule. monotonic(...) monotonic()->float Monotonicclock,cannotgobackward. monotonic_ns(...) monotonic_ns()->int Monotonicclock,cannotgobackward,asnanoseconds. perf_counter(...) perf_counter()->float Performancecounterforbenchmarking. perf_counter_ns(...) perf_counter_ns()->int Performancecounterforbenchmarkingasnanoseconds. process_time(...) process_time()->float Processtimeforprofiling:sumofthekernelanduser-spaceCPUtime. process_time_ns(...) process_time()->int Processtimeforprofilingasnanoseconds: sumofthekernelanduser-spaceCPUtime. sleep(...) sleep(seconds) Delayexecutionforagivennumberofseconds.Theargumentmaybe afloatingpointnumberforsubsecondprecision. strftime(...) strftime(format[,tuple])->string Convertatimetupletoastringaccordingtoaformatspecification. Seethelibraryreferencemanualforformattingcodes.Whenthetimetuple isnotpresent,currenttimeasreturnedbylocaltime()isused. Commonlyusedformatcodes: %YYearwithcenturyasadecimalnumber. %mMonthasadecimalnumber[01,12]. %dDayofthemonthasadecimalnumber[01,31]. %HHour(24-hourclock)asadecimalnumber[00,23]. %MMinuteasadecimalnumber[00,59]. %SSecondasadecimalnumber[00,61]. %zTimezoneoffsetfromUTC. %aLocale'sabbreviatedweekdayname. %ALocale'sfullweekdayname. %bLocale'sabbreviatedmonthname. %BLocale'sfullmonthname. %cLocale'sappropriatedateandtimerepresentation. %IHour(12-hourclock)asadecimalnumber[01,12]. %pLocale'sequivalentofeitherAMorPM. Othercodesmaybeavailableonyourplatform.Seedocumentationfor theClibrarystrftimefunction. strptime(...) strptime(string,format)->struct_time Parseastringtoatimetupleaccordingtoaformatspecification. Seethelibraryreferencemanualforformattingcodes(sameas strftime()). Commonlyusedformatcodes: %YYearwithcenturyasadecimalnumber. %mMonthasadecimalnumber[01,12]. %dDayofthemonthasadecimalnumber[01,31]. %HHour(24-hourclock)asadecimalnumber[00,23]. %MMinuteasadecimalnumber[00,59]. %SSecondasadecimalnumber[00,61]. %zTimezoneoffsetfromUTC. %aLocale'sabbreviatedweekdayname. %ALocale'sfullweekdayname. %bLocale'sabbreviatedmonthname. %BLocale'sfullmonthname. %cLocale'sappropriatedateandtimerepresentation. %IHour(12-hourclock)asadecimalnumber[01,12]. %pLocale'sequivalentofeitherAMorPM. Othercodesmaybeavailableonyourplatform.Seedocumentationfor theClibrarystrftimefunction. thread_time(...) thread_time()->float Threadtimeforprofiling:sumofthekernelanduser-spaceCPUtime. thread_time_ns(...) thread_time()->int Threadtimeforprofilingasnanoseconds: sumofthekernelanduser-spaceCPUtime. time(...) time()->floatingpointnumber ReturnthecurrenttimeinsecondssincetheEpoch. Fractionsofasecondmaybepresentifthesystemclockprovidesthem. time_ns(...) time_ns()->int ReturnthecurrenttimeinnanosecondssincetheEpoch. DATA altzone=-32400 daylight=0 timezone=-28800 tzname=('中国标准时间','中国夏令时') FILE (built-in) None Processfinishedwithexitcode0
那么接下来我们挨个来看看
1.time.time()为当前时间戳,从1900年开始到当前时间的秒数
print(help(time.time))#打印帮助信息 print(time.time())#1610720236.653394#打印当前时间戳
Helponbuilt-infunctiontimeinmoduletime: time(...) time()->floatingpointnumber ReturnthecurrenttimeinsecondssincetheEpoch. Fractionsofasecondmaybepresentifthesystemclockprovidesthem. None 1610727247.1696546
2.time.sleep(secs)让程序暂停secs秒
1print(help(time.sleep))#打印帮助信息 2time.sleep(3)#暂停3秒
Helponbuilt-infunctionsleepinmoduletime: sleep(...) sleep(seconds) Delayexecutionforagivennumberofseconds.Theargumentmaybe afloatingpointnumberforsubsecondprecision. None
3.time.gmtime()结构化时间,不过要注意的一点是这个时间是世界标准时间(格林尼治时间)
1print(help(time.gmtime))#打印帮助信息 2print(time.gmtime())#结构化时间time.struct_time(tm_year=2021,tm_mon=1,tm_mday=15,tm_hour=14,tm_min=22,tm_sec=30,tm_wday=4,tm_yday=15,tm_isdst=0)
Helponbuilt-infunctiongmtimeinmoduletime: gmtime(...) gmtime([seconds])->(tm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst) ConvertsecondssincetheEpochtoatimetupleexpressingUTC(a.k.a. GMT).When'seconds'isnotpassedin,convertthecurrenttimeinstead. Iftheplatformsupportsthetm_gmtoffandtm_zone,theyareavailableas attributesonly. None time.struct_time(tm_year=2021,tm_mon=1,tm_mday=15,tm_hour=16,tm_min=16,tm_sec=39,tm_wday=4,tm_yday=15,tm_isdst=0)
不过这时肯定有人该问了,那我们的当地时间怎么表示呢,所以我们来介绍下一个
4.time.localtime()结构化时间,当前时间
1print(help(time.localtime))#打印帮助信息 2print(time.localtime())#当前结构化时间
Helponbuilt-infunctionlocaltimeinmoduletime: localtime(...) localtime([seconds])->(tm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst) ConvertsecondssincetheEpochtoatimetupleexpressinglocaltime. When'seconds'isnotpassedin,convertthecurrenttimeinstead. None time.struct_time(tm_year=2021,tm_mon=1,tm_mday=16,tm_hour=0,tm_min=17,tm_sec=49,tm_wday=5,tm_yday=16,tm_isdst=0)
总说结构化时间,那结构化时间是什么呢,我们来看看里面的参数
我们来拿上面这个例子来解释:
tm_year=2021 当前所在年
tm_mon=1 当前所在月
tm_mday=15 当前所在天
tm_hour=23 当前所在时
tm_min=18 当前所在分
tm_sec=57 当前所在秒
tm_wday=4 当前周的第几天
tm_yday=15 当前年的第几天
但是有时候我们需要的并不是结构化时间,而是类似于2021-01-1523:28:26这样的格式化时间,那我们应该怎么做呢?
6.time.strftime()将结构话时间化为格式化时间
1print(help(time.strftime))#打印帮助信息 2struct_time=time.localtime() 3print(time.strftime("%Y-%m-%d%H:%M:%S",struct_time))#格式化时间
Helponbuilt-infunctionstrftimeinmoduletime: strftime(...) strftime(format[,tuple])->string Convertatimetupletoastringaccordingtoaformatspecification. Seethelibraryreferencemanualforformattingcodes.Whenthetimetuple isnotpresent,currenttimeasreturnedbylocaltime()isused. Commonlyusedformatcodes: %YYearwithcenturyasadecimalnumber. %mMonthasadecimalnumber[01,12]. %dDayofthemonthasadecimalnumber[01,31]. %HHour(24-hourclock)asadecimalnumber[00,23]. %MMinuteasadecimalnumber[00,59]. %SSecondasadecimalnumber[00,61]. %zTimezoneoffsetfromUTC. %aLocale'sabbreviatedweekdayname. %ALocale'sfullweekdayname. %bLocale'sabbreviatedmonthname. %BLocale'sfullmonthname. %cLocale'sappropriatedateandtimerepresentation. %IHour(12-hourclock)asadecimalnumber[01,12]. %pLocale'sequivalentofeitherAMorPM. Othercodesmaybeavailableonyourplatform.Seedocumentationfor theClibrarystrftimefunction. None 2021-01-1600:18:38
同样这里为什么要写成"%Y-%m-%d%H:%M:%S"呢,就是为了控制时间的格式。
那这些都表示什么呢,我们来看看
%Y Yearwithcenturyasadecimalnumber.
%m Monthasadecimalnumber[01,12].
%d Dayofthemonthasadecimalnumber[01,31].
%H Hour(24-hourclock)asadecimalnumber[00,23].
%M Minuteasadecimalnumber[00,59].
%S Secondasadecimalnumber[00,61].
%z TimezoneoffsetfromUTC.
%a Locale'sabbreviatedweekdayname.
%A Locale'sfullweekdayname.
%b Locale'sabbreviatedmonthname.
%B Locale'sfullmonthname.
%c Locale'sappropriatedateandtimerepresentation.
%I Hour(12-hourclock)asadecimalnumber[01,12].
%p Locale'sequivalentofeitherAMorPM.
不过似乎也可以单独使用 time.strftime(),我们来看看结果,但是我们必须要把格式加上,如下所示:
print(time.strftime("%Y-%m-%d%H:%M:%S"))#格式化时间 #2021-01-1523:36:49
那么,有时候我们也需要把格式化时间转化为结构化时间来使用,这时我们仅仅需要看看接下来的知识就能掌握
7.time.strptime()将格式化时间(字符串)转化为结构化时间
print(help(time.strftime)) print(time.strftime("%Y-%m-%d%H:%M:%S"))#格式化时间 #2021-01-1523:36:49
Helponbuilt-infunctionstrftimeinmoduletime: strftime(...) strftime(format[,tuple])->string Convertatimetupletoastringaccordingtoaformatspecification. Seethelibraryreferencemanualforformattingcodes.Whenthetimetuple isnotpresent,currenttimeasreturnedbylocaltime()isused. Commonlyusedformatcodes: %YYearwithcenturyasadecimalnumber. %mMonthasadecimalnumber[01,12]. %dDayofthemonthasadecimalnumber[01,31]. %HHour(24-hourclock)asadecimalnumber[00,23]. %MMinuteasadecimalnumber[00,59]. %SSecondasadecimalnumber[00,61]. %zTimezoneoffsetfromUTC. %aLocale'sabbreviatedweekdayname. %ALocale'sfullweekdayname. %bLocale'sabbreviatedmonthname. %BLocale'sfullmonthname. %cLocale'sappropriatedateandtimerepresentation. %IHour(12-hourclock)asadecimalnumber[01,12]. %pLocale'sequivalentofeitherAMorPM. Othercodesmaybeavailableonyourplatform.Seedocumentationfor theClibrarystrftimefunction. None 2021-01-1600:20:46
当然以上只是一个举例,具体我们可以采用如下方式:
a=time.strptime("2021-01-1522:26:28","%Y-%m-%d%H:%M:%S") print(a.tm_yday)#15 print(a.tm_wday)#4
最后,我们快接近了尾声,最后我们再介绍两个就结束了
8.time.ctime()将所给时间戳转变为一个格式化时间
1print(help(time.ctime))#将时间戳转变为一个格式化时间 2print(time.ctime())#如果不带参数则默认为当前时间戳 3print(time.ctime(12412415))
Helponbuilt-infunctionctimeinmoduletime: ctime(...) ctime(seconds)->string ConvertatimeinsecondssincetheEpochtoastringinlocaltime. Thisisequivalenttoasctime(localtime(seconds)).Whenthetimetupleis notpresent,currenttimeasreturnedbylocaltime()isused. None SatJan1600:21:562021 SunMay2423:53:351970
9.time.mktime() 将所给结构化时间转化为时间戳
1print(help(time.ctime))#打印帮助信息 2print(time.mktime(time.localtime()))#将结构化时间转化为时间戳
Helponbuilt-infunctionctimeinmoduletime: ctime(...) ctime(seconds)->string ConvertatimeinsecondssincetheEpochtoastringinlocaltime. Thisisequivalenttoasctime(localtime(seconds)).Whenthetimetupleis notpresent,currenttimeasreturnedbylocaltime()isused. None 1610727764.0
不过值得一提的是,这种方式得到的时间戳精度要比time.time()低的多
最后,在提供一种其他求当前时间的方法
importdatetime print(datetime.datetime.now())#2021-01-1523:55:48.985808
本次time模块便到此结束,其他模块下次讲解
总结
到此这篇关于Python学习之time模块的基本使用的文章就介绍到这了,更多相关Pythontime模块内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!