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!
延伸文章資訊
- 1Convert datetime object to milliseconds since epoch in Python
A simple solution is to get the timedelta object by finding the difference of the given datetime ...
- 2millisecond python datetime Code Example
from datetime import datetime. 2. . 3. print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[...
- 3Python: Convert timedelta to milliseconds - thisPointer
This article will discuss how we can convert the datetime module's timedelta object to total mill...
- 4How to use strptime with milliseconds in Python
- 5python datetime milliseconds Code Example
“python datetime milliseconds” Code Answer's ; 1. from datetime import datetime ; 2. ; 3. print...