Format a datetime into a string with milliseconds - Stack ...

文章推薦指數: 80 %
投票人數:10人

With Python 3.6 you can use: from datetime import datetime datetime.utcnow().isoformat(sep=' ', timespec='milliseconds'). Output: Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Formatadatetimeintoastringwithmilliseconds AskQuestion Asked 10years,5monthsago Modified 1monthago Viewed 569ktimes 256 44 Iwanttohaveadatetimestringfromthedatewithmilliseconds.ThiscodeistypicalformeandI'meagertolearnhowtoshortenit. fromdatetimeimportdatetime timeformatted=str(datetime.utcnow()) semiformatted=timeformatted.replace("-","") almostformatted=semiformatted.replace(":","") formatted=almostformatted.replace(".","") withspacegoaway=formatted.replace("","") formattedstripped=withspacegoaway.strip() printformattedstripped pythondatetimestring-formattingmilliseconds Share Improvethisquestion Follow editedJan23at8:11 peak 85.2k1414goldbadges117117silverbadges142142bronzebadges askedSep28,2011at19:28 JurudocsJurudocs 7,3051919goldbadges5959silverbadges8686bronzebadges 3 1 stackoverflow.com/questions/311627/… – cetver Sep28,2011at19:31 3 Pleasewriteatitlethatdescribesyourproblemandtrytokeepyourquestionclearandtothepoint. – agf Sep28,2011at19:34 2 It'sworthmentioningherethatextraprecisionisoftenjustfine.Forexample,Java'sInstant.parsecanparserepresenationcreatedwithstrftime('%Y-%m-%dT%H:%M:%S.%fZ') – JarekPrzygódzki Mar8,2017at9:03 Addacomment  |  14Answers 14 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 500 Togetadatestringwithmilliseconds(3decimalplacesbehindseconds),usethis: fromdatetimeimportdatetime printdatetime.utcnow().strftime('%Y-%m-%d%H:%M:%S.%f')[:-3] >>>>OUTPUT>>>> 2020-05-0410:18:32.926 Note:ForPython3,printrequiresparentheses: print(datetime.utcnow().strftime('%Y-%m-%d%H:%M:%S.%f')[:-3]) Share Improvethisanswer Follow editedJan28,2020at16:05 answeredAug23,2013at15:20 JeremyMoritzJeremyMoritz 11.9k77goldbadges3535silverbadges4040bronzebadges 9 7 Note,ifyouwanttouseimportdatetimeinsteadoffromdatetimeimportdatetime,you'llhavetousethis:datetime.datetime.utcnow().strftime("%H:%M:%S.%f") – Luc Sep16,2015at11:01 22 Incasemicrosecondsare0,inwindows2.7implementationmicrosecondsarenotprintedoutsoittrimsseconds:( – cabbi Nov9,2015at15:37 15 notethatthistruncates,notroundstomilliseconds – gens Oct1,2017at18:11 3 Asgensmentions,won'tthisgetitwrongitthefirstdropsnumberis>=5?.Infactiftheusecpartis>999500,thenyouwillnevergetthetimerightbyfiddlingwithmicrosecondspart – Chris Nov21,2017at1:11 3 @gensfortime,truncationispreferredtorounding.E.g.07:59:59.999shouldbetruncatedto07:59:59or07:59insteadofroundingto08:00:00or08:00,justas07:59:59shouldbetruncatedto07:59insteadofroundingto08:00. – Technophile Jul1,2021at21:59  |  Show4morecomments 120 WithPython3.6youcanuse: fromdatetimeimportdatetime datetime.utcnow().isoformat(sep='',timespec='milliseconds') Output: '2019-05-1009:08:53.155' Moreinfohere:https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat Share Improvethisanswer Follow answeredMay10,2019at9:15 LorenzoLorenzo 1,20111goldbadge66silverbadges33bronzebadges 2 2 Usefulwithtimezonetoo:date=datetime(2019,5,10)date_with_tz=pytz.timezone('Europe/Rome').localize(date)date_with_tz.isoformat(sep='T',timespec='milliseconds')output:'2019-05-10T00:00:00.000+02:00' – Ena May10,2019at9:17 Thislookscleanerthanthe[:-3]intheacceptedanswer,butyoushouldknowthatitseeminglydoesthesame>>>datetime.fromisoformat('2021-12-0820:00:00.678900').isoformat(sep='',timespec='milliseconds')leadsto'2021-12-0820:00:00.678'.IsthetruncationspecifiedinISOstandardorisitjustabug?Theimplementationusesintegerdivision:github.com/python/cpython/blob/… – Wolf Dec8,2021at19:00 Addacomment  |  29 printdatetime.utcnow().strftime('%Y%m%d%H%M%S%f') http://docs.python.org/library/datetime.html#strftime-strptime-behavior Share Improvethisanswer Follow answeredSep28,2011at19:35 knittiknitti 6,5612828silverbadges4242bronzebadges 4 17 FYI,thisprintsmicrosecondsasthelast6digits.Add[:-3]totheendtodropthelast3digitssothatitisonlydisplayingmilliseconds. – MarkLakata Jan2,2014at21:40 6 microsecondscanbelessthan6digits,so[:-3]isprintingoutwrongmilliseconds – cabbi Nov9,2015at15:26 14 whatifwehavetimezone? – ᐅdevrimbaris Mar4,2017at11:38 1 @ᐅdevrimbarisfortimezonecheckoutLorenzo'sanswer – Ena May10,2019at9:18 Addacomment  |  27 @Cabbiraisedtheissuethatonsomesystems,themicrosecondsformat%fmaygive"0",soit'snotportabletosimplychopoffthelastthreecharacters. Thefollowingcodecarefullyformatsatimestampwithmilliseconds: fromdatetimeimportdatetime (dt,micro)=datetime.utcnow().strftime('%Y-%m-%d%H:%M:%S.%f').split('.') dt="%s.%03d"%(dt,int(micro)/1000) printdt ExampleOutput: 2016-02-2604:37:53.133 TogettheexactoutputthattheOPwanted,wehavetostrippunctuationcharacters: fromdatetimeimportdatetime (dt,micro)=datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.') dt="%s%03d"%(dt,int(micro)/1000) printdt ExampleOutput: 20160226043839901 Share Improvethisanswer Follow editedFeb26,2016at4:39 answeredFeb26,2016at4:32 SamWatkinsSamWatkins 7,13233goldbadges3737silverbadges3838bronzebadges 2 9 WhatI'amactuallydoingisthis:print'%s.%03d'%(dt.strftime("%Y-%m-%d%H:%M:%S"),int(dt.microsecond/1000)) – cabbi Mar8,2016at8:35 3 agreewith@cabbi,there'snoneedtoconvertbackandforthwithstringandint – caoanan May21,2018at3:15 Addacomment  |  8 Probablylikethis: importdatetime now=datetime.datetime.now() now.strftime('%Y/%m/%d%H:%M:%S.%f')[:-3] #[:-3]=>Removingthe3lastcharactersas%fisformicrosecs. Share Improvethisanswer Follow editedJun11,2018at9:04 MichaelDorner 13.9k1010goldbadges7373silverbadges104104bronzebadges answeredDec4,2013at16:50 NFayçalNFayçal 9911silverbadge66bronzebadges 1 1 Asmentionedinotheranswers,ifmicrosecondsare0thenthe".123455"portionmaybeprintedas".0",causingtruncationofthelast3charstoeatthelowsecondsdigitand".0". – Technophile Jul1,2021at22:06 Addacomment  |  5 importdatetime #convertstringintodatetimeformat. str_date='2016-10-0615:14:54.322989' d_date=datetime.datetime.strptime(str_date,'%Y-%m-%d%H:%M:%S.%f') print(d_date) print(type(d_date))#checkd_datetype. #convertdatetimetoregularformat. reg_format_date=d_date.strftime("%d%B%Y%I:%M:%S%p") print(reg_format_date) #someotherdateformats. reg_format_date=d_date.strftime("%Y-%m-%d%I:%M:%S%p") print(reg_format_date) reg_format_date=d_date.strftime("%Y-%m-%d%H:%M:%S") print(reg_format_date) <<<<<>>>>>> 2016-10-0615:14:54.322989 06October201603:14:54PM 2016-10-0603:14:54PM 2016-10-0615:14:54 Share Improvethisanswer Follow answeredOct6,2016at8:15 WaqasAliWaqasAli 1,33122goldbadges1616silverbadges2525bronzebadges 0 Addacomment  |  2 Iassumeyoumeanyou'relookingforsomethingthatisfasterthandatetime.datetime.strftime(),andareessentiallystrippingthenon-alphacharactersfromautctimestamp. You'reapproachismarginallyfaster,andIthinkyoucanspeedthingsupevenmorebyslicingthestring: >>>importtimeit >>>t=timeit.Timer('datetime.utcnow().strftime("%Y%m%d%H%M%S%f")',''' ...fromdatetimeimportdatetime''') >>>t.timeit(number=10000000) 116.15451288223267 >>>defreplaceutc(s): ...returns\ ....replace('-','')\ ....replace(':','')\ ....replace('.','')\ ....replace('','')\ ....strip() ... >>>t=timeit.Timer('replaceutc(str(datetime.datetime.utcnow()))',''' ...from__main__importreplaceutc ...importdatetime''') >>>t.timeit(number=10000000) 77.96774983406067 >>>defsliceutc(s): ...returns[:4]+s[5:7]+s[8:10]+s[11:13]+s[14:16]+s[17:19]+s[20:] ... >>>t=timeit.Timer('sliceutc(str(datetime.utcnow()))',''' ...from__main__importsliceutc ...fromdatetimeimportdatetime''') >>>t.timeit(number=10000000) 62.378515005111694 Share Improvethisanswer Follow answeredSep28,2011at20:33 AustinMarshallAustinMarshall 2,8211313silverbadges1414bronzebadges 2 @oxtopusGoodwork.Personally,Idon'tusetimeitanymoreforsimplemeasuringoftime.It'sstrangethattheratiosoftimesaredifferentwithyourcode:1-0.67-0.53andwithmine:1-0.35-0.20,forthemethodsstrftime-replace-slicing – eyquem Sep28,2011at21:47 Maybesomethingtodowiththestr(datetime.datetime.utcnow())beingcalledineachiterationofthetestvssettingitonce? – AustinMarshall Sep28,2011at22:10 Addacomment  |  2 Inpython3.6andaboveusingpythonf-strings: fromdatetimeimportdatetime i=datetime.utcnow() print(f"""{i:%Y-%m-%d%H:%M:%S}.{"{:03d}".format(i.microsecond//1000)}""") Thecodespecifictoformatmillisecondsis: {"{:03d}".format(i.microsecond//1000)} Theformatstring{:03d}andmicrosecondtomillisecondconversion//1000isfromdef_format_timeinhttps://github.com/python/cpython/blob/master/Lib/datetime.pythatisusedfordatetime.datetime.isoformat(). Share Improvethisanswer Follow answeredOct2,2020at7:38 user1004488user1004488 2111bronzebadge Addacomment  |  1 fromdatetimeimportdatetime fromtimeimportclock t=datetime.utcnow() print't==%s%s\n\n'%(t,type(t)) n=100000 te=clock() foriinxrange(1): t_stripped=t.strftime('%Y%m%d%H%M%S%f') printclock()-te printt_stripped,"t.strftime('%Y%m%d%H%M%S%f')" print te=clock() foriinxrange(1): t_stripped=str(t).replace('-','').replace(':','').replace('.','').replace('','') printclock()-te printt_stripped,"str(t).replace('-','').replace(':','').replace('.','').replace('','')" print te=clock() foriinxrange(n): t_stripped=str(t).translate(None,'-:.') printclock()-te printt_stripped,"str(t).translate(None,'-:.')" print te=clock() foriinxrange(n): s=str(t) t_stripped=s[:4]+s[5:7]+s[8:10]+s[11:13]+s[14:16]+s[17:19]+s[20:] printclock()-te printt_stripped,"s[:4]+s[5:7]+s[8:10]+s[11:13]+s[14:16]+s[17:19]+s[20:]" result t==2011-09-2821:31:45.562000 3.33410112179 20110928212155046000t.strftime('%Y%m%d%H%M%S%f') 1.17067364707 20110928212130453000str(t).replace('-','').replace(':','').replace('.','').replace('','') 0.658806915404 20110928212130453000str(t).translate(None,'-:.') 0.645189262881 20110928212130453000s[:4]+s[5:7]+s[8:10]+s[11:13]+s[14:16]+s[17:19]+s[20:] Useoftranslate()andslicingmethodruninsametime translate()presentstheadvantagetobeusableinoneline Comparingthetimesonthebasisofthefirstone: 1.000*t.strftime('%Y%m%d%H%M%S%f') 0.351*str(t).replace('-','').replace(':','').replace('.','').replace(' ','') 0.198*str(t).translate(None,'-:.') 0.194*s[:4]+s[5:7]+s[8:10]+s[11:13]+s[14:16]+s[17:19]+ s[20:] Share Improvethisanswer Follow editedSep28,2011at21:52 answeredSep28,2011at21:36 eyquemeyquem 25.4k66goldbadges3636silverbadges4343bronzebadges 1 1 Nice!Thatisindeedcleanerwithoutsacrificingperformance.str.translate()actuallyfasterinmytesting. – AustinMarshall Sep28,2011at21:47 Addacomment  |  1 Idealtwiththesameproblembutinmycaseitwasimportantthatthemillisecondwasroundedandnottruncated fromdatetimeimportdatetime,timedelta defstrftime_ms(datetime_obj): y,m,d,H,M,S=datetime_obj.timetuple()[:6] ms=timedelta(microseconds=round(datetime_obj.microsecond/1000.0)*1000) ms_date=datetime(y,m,d,H,M,S)+ms returnms_date.strftime('%Y-%m-%d%H:%M:%S.%f')[:-3] Share Improvethisanswer Follow answeredJul28,2015at22:37 omdanielomdaniel 1111bronzebadge Addacomment  |  1 python-c"fromdatetimeimportdatetime;printstr(datetime.now())[:-3]" 2017-02-0910:06:37.006 Share Improvethisanswer Follow answeredFeb9,2017at18:09 arntgarntg 1,4391313silverbadges1212bronzebadges Addacomment  |  1 datetime t=datetime.datetime.now() ms='%s.%i'%(t.strftime('%H:%M:%S'),t.microsecond/1000) print(ms) 14:44:37.134 Share Improvethisanswer Follow answeredMar5,2019at14:45 HunaphuHunaphu 32055silverbadges77bronzebadges Addacomment  |  0 Theproblemwithdatetime.utcnow()andothersuchsolutionsisthattheyareslow. Moreefficientsolutionmaylooklikethisone: def_timestamp(prec=0): t=time.time() s=time.strftime("%H:%M:%S",time.localtime(t)) ifprec>0: s+=("%.9f"%(t%1,))[1:2+prec] returns Whereprecwouldbe3inyourcase(milliseconds). Thefunctionworksupto9decimalplaces(pleasenotenumber9inthe2ndformattingstring). Ifyou'dliketoroundthefractionalpart,I'dsuggestbuilding"%.9f"dynamicallywithdesirednumberofdecimalplaces. Share Improvethisanswer Follow answeredAug7,2019at13:19 matomato 54533silverbadges1010bronzebadges Addacomment  |  0 Ifyouarepreparedtostorethetimeinavariableanddoalittlestringmanipulation,thenyoucanactuallydothiswithoutusingthedatetimemodule. >>>_now=time.time() >>>print("Time:%s.%s\n"%(time.strftime('%x%X',time.localtime(_now)), ...str('%.3f'%_now).split('.')[1]))#Roundstonearestmillisecond Time:05/02/2101:16:58.676 >>> %.3fwillroundtooutputthenearestmillisecond,ifyouwantmoreorlessprecisionjustchangethenumberofdecimalplaces >>>print("Time:%s.%s\n"%(time.strftime('%x%X',time.localtime(_now)), ...str('%.1f'%_now).split('.')[1]))#Roundstonearesttenthofasecond Time:05/02/2101:16:58.7 >>> TestedinPython2.7and3.7(obviouslyyouneedtoleaveoutthebracketswhencallingprintinversion2.x). Share Improvethisanswer Follow editedMay2,2021at17:26 answeredMay2,2021at0:26 MikeT.MikeT. 1191111bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythondatetimestring-formattingmillisecondsoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 0 Howtogetaccesstothemillisecondlevelclock? 772 Howtoprintadateinaregularformat? 7 Pythondisplaymillisecondsinformattedstringusing`time.strftime` 5 Formatsecondsasfloat 0 pythonstrippingcharsfromlistitem 0 UnabletoprocessJSONinputwheningestinglogstoOracle -2 Convertingadateandtimeformatinpython 2 Setprecisionformillisecondsindatetimestring:Python 0 Whydoesnotdatetimeobjecthaveamillsecondunit? 2 GenerateTimestampwithmillisecondfrequencyinPython Seemorelinkedquestions Related 2183 Callingafunctionofamodulebyusingitsname(astring) 6192 HowdoImergetwodictionariesinasingleexpression(takeunionofdictionaries)? 2966 ShouldIusethedatetimeortimestampdatatypeinMySQL? 2723 Convertingstringintodatetime 3246 Convertbytestoastring 3417 HowdoIsortadictionarybyvalue? 2059 Importingfilesfromdifferentfolder 1419 Stringformatting:%vs..formatvs.f-stringliteral 1228 Howtoreadatextfileintoastringvariableandstripnewlines? 3304 HowtoiterateoverrowsinaDataFrameinPandas HotNetworkQuestions Isitimpolitetosendtheprofessorapre-writtenletterofrecommendationforapproval? Minussignnotaligningwithfraction Howtogetamotorcycletoaskillstest Isthereanyexampleofadependentproductthatmakessenseinanon-type-theorycontext? Aproverbthatexpressestheideathatanunaddressedproblemwillleadtoconsequences? Palindromefromthefirst20numbers Surprisingapplicationsofthetheoryofgames? Howcanfourbethehalfoffive? Convertbetweengraphrepresentations Meaningof"orwehaveheadphonesorwedon't,so..." Does7-ZipreallyrunmultipleroundsofSHA-256whenkeystretching? Retainingambitiousemployeewithrareskillset TheITstaffsaysthatlinuxcannotconnecttotheschool'sinternetandrefusetotry Ifplanetsareellipsoidswhydon'twehave3diameters? Iturnedabreakeroff,andnowthesecurityalarmsystemwon’tstopbeeping My(manual)transmissionwon'tengageanygear1dayafterescapingbog ReturningMTBrider,lookingforadviceonpurchasinganewMTB WhatisthesyntaxtosearchQATforwordswhenreversedformanewword(i.e.notapalindrome)? Fallout4chemistryworkstation-backgroundimageusedforreflections IfplayerAisincheckbuthasamovewhichwillcheckmateplayerBwithoutexitingcheck,isthatmovelegal? DrawtheUkrainianFlag Howtomotivatestafftoattendapaidcertification? Willunevenspeedberoundedupordown? Howtodrainatoiletbowl? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?