Python Get Milliseconds - Finxter
文章推薦指數: 80 %
datetime.datetime.now(). This function returns the current system date and time with the following attributes: year, ... Skiptocontent Menu Inthisarticlewearegoingtolookathowwecanseetimeinmilliseconds, i.e.onethousandth(1000th)ofasecond,usingPython.Thiscouldbeforpurecuriosity,benchmarkingcodeortoget avery,veryaccuratetimeofday– whateverthereason,thefocusofthearticleishowtogetthetimeinmilliseconds,ratherthanwhatit’stobeusedforoncewehaveit. TableofContents Method1:MillisecondsandFixedTimeUsingtime.time()time.time_ns()Method2:MillisecondsandRelativeTimetime.monotonic_ns() time.perf_counter_ns()Method3:MillisecondsandTimeofDaydatetime.datetime.now()datetime.datetime.utcnow()Summary Method1:MillisecondsandFixedTime Thefirstmethodwearegoingtolookatisbasedonmeasuringhowmuchtimehaspassedsinceafixedpointintime,whichwecallthe‘epoch’.ForPython,andcomputingingeneral,the epochisthepointwheretimestartsandthepassageoftimeisthereforemeasuredagainstthis.Whilsttheepochcanvarydependingonoperatingsystem, forUnixandWindowsitismidnightonJanuary1st1970inUTCtime(GreenwichMeanTimewithoutDaylightSavingstimeadjustments). Ifyouwanttofindoutwhattheepochtimeisonagivenplatformyoucanuse: importtime time.gmtime(0) #time.struct_time(tm_year=1970,tm_mon=1,tm_mday=1,tm_hour=0,tm_min=0,tm_sec=0,tm_wday=3,tm_yday=1,tm_isdst=0) AsIamusingaWindows10machinetheaboveoutputjustconfirmsthatthestarttime,ortheepochforPythononmymachineisJanuary1,1970,00:00:00. Usingtime.time() ThetimePythonStandardLibrarycanbeusedtoreturnthetimeinsecondssincetheepochasafloatingpointnumber: importtime time.time() #1613649533.180575 Thisessentiallygivesusthenumberofsecondsthathavepassedsincetheepoch,sotogetthetimeinmillisecondswehavetomultiply thevaluereturnedby1000.Foraestheticswecanroundthenumberandconverttoaninteger: importtime int(round(time.time()*1000)) #1613649588303 Whilstthisisagood,basicwayofgettingtime,ifyouaremeasuringtimeinmillisecondsyouareprobablylookingforalevelofprecisionthisdoesnotprovide.Unfortunately,thetime.timeisdesignedtogettimeinseconds,socannotguaranteethatthesystemyouareusingwillreturnatimewithaprecisiongreaterthanthati.e1second. time.time_ns() Appreciatingthisneedformoreaccuracy,Pythonversions3.7andlaterincorporateanadditionaltimefunctionthatmeasurestimetothenanosecond–athousand-millionthofasecond.Youmay,likeme,justneedamomenttothinkaboutthat–athousand-millionthofasecond… So,whilstthismethodclearlyhastheprecisionwearelookingfor,togetthetimeinmillisecondswestillneedtodividethenumberreturnedby1,000,000(i.econvertnanosecondstomilliseconds): importtime time.time_ns()//1000000 #1613649695449 Asthefunctionautomaticallyreturnsanintegerwedonotneedtoworryaboutroundingorconverting. Method2:MillisecondsandRelativeTime Ifouraimistomeasurespeedinmilliseconds,forbenchmarkingcodeforexample,Pythonhasmultiplefunctionsinthetimelibrarythatcanspecificallyhelpwiththis.Wearegoingtolookattwo,inparticular,whichcanbeusedto measuretimeinnanosecondssogiveustheprecisionwerequire. UnliketheexamplesinMethod1,neitherofthesefunctionshaveadefinedrelationshiptothereal-worldtime– theepoch,theylookatwhatwecallrelativetime.Thevaluetheyreturnisnotdefinedagainstanystartingpoint, butcanbeusedtomeasuretimeintervals–suchashowlongittakestorunataskorspecificpieceofcode.. time.monotonic_ns() Thisfunctionisusedtogetthevalueofamonotonicclock, aclockthatcannotgobackwardsandisnotaffectedbysystemclockupdates. Asthereturnvalueisundefined,i.ewedon’tknowwhatstartingpointitrelatesto,ithaslimiteduseonit’sown.However, wecansandwichsomecodebetweenconsecutivecallstomeasurethetimebetweenthecallsandthereforehowlongittooktoexecuteourcode. Intheexamplebelow,wewillprintthestartmonotonictimeandthefinishmonotonictimeforillustrationpurposesastheyhavenovalueontheirown.WecanhoweverusethemtomeasurethetimebetweenthetwocallstoseehowlongittookforPythontoperformtheprintfunction.Asthereturnvalueisinnanoseconds, wehavetodivideby1,000,000togetourmillisecondresponsetime importtime start=time.monotonic_ns() print(start) x=1 while(x<=100): print(x) x+=1 finish=time.monotonic_ns() duration=finish-start print(f"Thattook{duration//1000000}ms") Theoutputis: 176278031000000 1 2 3 .. 98 99 100 176278046000000 Thattook15ms time.perf_counter_ns() Thismethodissimilartothetime.monotonicfunctionpreviouslyoutlinedbut,asthenamesuggests,isaperformancecounter. Itdoesnotincludetimeelapsedduringsleepandissystem-wide.Thisreturnstheabsolutevalueofthecounterbutasthisreturnisundefined,aswiththetime.monotonicfunction, ithaslimiteduseonit’sown. So,aswiththetime.monotonicfunctionwecanuseconsecutivecallstomeasuretimebetweenthecalls, and asthereturnisinnanosecondswehavetodivideby1,000,000togetmilliseconds: importtime start=time.perf_counter_ns() print(start) x=1 while(x<=100): print(x) x+=1 finish=time.perf_counter_ns() print(finish) duration=finish-start print(f"Thattook{duration//1000000}ms") Theoutputis: 80058697360400 1 2 3 .. 98 99 100 80058701461500 Thattook4ms Withboththetime.perf_counterandtime.monotonicfunctions,thestartandfinishtimeswehaveprintedareirrelevantontheirown,becausewedonotknowwhattheyrelateto.Theironlyuseistoshowusthetimeelapsedbetweenthecalls. Method3:MillisecondsandTimeofDay Finally,wearegoingtolookathowwecangetPythontotellusthetimeofdayinmilliseconds,andtodothiswewillbeusingthePythonStandardLibrarydatetime. datetime.datetime.now() Thisfunctionreturnsthecurrentsystemdateandtimewiththefollowingattributes: year,month,day,hour,minute,second,microsecond Ifwejustcallthefunctionbyitselfitwillshowusthecurrentdateandtimeatmylocation,downtothemicrosecond(onemillionthofasecond): importdatetime datetime.datetime.now() #datetime.datetime(2021,2,18,12,21,7,163392) Theaboveoutputtellsmecurrentlocaltimeis Year:2021Month:2(February)Day:18Hour:12Minutes:21Seconds:7Microseconds:163392 Thethingtobearisthatthemicorsecondattributebeingreturnedisalwaysinrelationtothesecondsattribute. Nowifwewanttoconvertthemicrosecondstomillisecondswehavetodivideby1000,wecanalsouseaprintstatementtohelpformatthefunctionforreadability: importdatetime dt=datetime.datetime.now() print(dt) dt.microsecond/1000 Theoutputis: 2021-02-1812:21:59.889660 889.66 Thefirstlineoftheoutputprintsthecurrentdateandtime,thesecondlineprintsthenumberofmillisecondsatthispoint. datetime.datetime.utcnow() Aslightvariationonthepreviousexampleisusingutcnow()insteadofjustnow().UTCreferstotimeinCoordinatedUniversalTimeorGreenwichMeanTime(GMT)andisusefultocalculateabsolutetimedifferenceswithouttheconfusionoftimezones.AsIliveinLondon,thereisnodifferenceinmycodebetweennow()andutcnow()butwewillseeitinactionanyway. Ifwecallthefunctionwithoutanyformattingwegetasimilaroutputtowhatwesawbefore,sotheattributesarethesame: importdatetime datetime.datetime.utcnow() #datetime.datetime(2021,2,18,12,22,45,343352) Wecouldgetourmillisecondsaswedidwiththenow()function,anditwouldworkjustaswell,butlet’shavealookatanothermethod.Inthisexamplewearegoingtousethestrftime()methodtoconvertourdatetimeobjectintoastring: importdatetime datetime.datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S:%f') #‘2021-02-18-12:23:34:474314' Asthelastnumberrepresentsmicrosecondsifwewanttodisplaythecurrenttimeinmillisecondswecandisregardthelast3digits,byslicing.Thishasthesameeffectasdividingby1000thusconvertingortimetomicroseconds: importdatetime print(datetime.datetime.utcnow().strftime('%Y-%m-%d-%H:%M:%S:%f')[:-3]) #2021-02-18-12:24:28:401 Summary WehavelookedatseveralwaysofusingPythontoshowustimeinmilliseconds.Whilsttheupdatefromthesimpletime.timetotime.time_nsdefinitelyhelpswithourprecision,itisdifficulttoproviderecommendationsonbestpractice.Allthemethodswehaveseenprovideananswer,butwhetherit’stherightanswerreallydependsonthequestionweareasking. Thekeyisfindingtherightmethodtofityourparticularrequirements,factorslikelevelofprecisionrequired,geographicallocation(s)andlevelofcomplexitywillalldeterminetherightapproach.LuckilyPythonhasanumberofwaystohelpusgetmilliseconds,soitcouldcomedowntopersonalpreference. WhyFinxter? "Givemealeverlongenough[...]andIshallmovetheworld."🌍-Archimedes Finxteraimstobeyourlever!Oursinglepurposeistoincreasehumanity'scollectiveintelligenceviaprogrammingtutorialssoyoucanleverageinfinitecomputationalintelligencetoyoursuccess!🧠 LearningResources Feelfreetojoinourfreeemailacademywith1000+tutorialsinPython,freelancing,datascienceandmachinelearning,andBlockchaintechnology! Also,feelfreetocheckoutourFinxterbooksandtheworld's#1freelancercoursetocreateyourthrivingcodingbusinessonline.⭐⭐⭐⭐⭐ FreelanceCoder Ifyou'renotquitereadytogoallin,readoverourblogarticleonearningyourfirst$3,000asafreelancecoder. ALLSIDEBARLINKSOPENINANEWTAB!
延伸文章資訊
- 1Python Get Milliseconds - Finxter
datetime.datetime.now(). This function returns the current system date and time with the followin...
- 2在Python 中將DateTime 轉換為帶有毫秒的字串
Python DateTime. 創建時間: February-07, 2021 | 更新時間: February-28, 2021. 使用 strftime() 方法將DateTime 格式化...
- 3Format a datetime into a string with milliseconds - Stack ...
With Python 3.6 you can use: from datetime import datetime datetime.utcnow().isoformat(sep=' ', t...
- 4Convert python datetime to timestamp in milliseconds - Stack Overflow
- 5Python: Get current time in milliseconds - w3resource
Python datetime: Exercise-12 with Solution. Write a Python program to get current time in millise...