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)
<<<<<