How to use strptime with milliseconds in Python

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

strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments :. Skiptocontent TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEventsCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonPythonprogramtoconvertalisttostringIterateoveralistinPythonReadafilelinebylineinPythonReadingandWritingtotextfilesinPythonPythonDictionaryPythonString|replace()Enumerate()inPythonsum()functioninPythonPrintlistsinPython(4DifferentWays)DifferentwaystocreatePandasDataframeisupper(),islower(),lower(),upper()inPythonandtheirapplicationsPython|GetalistasinputfromuserPythonListsConvertintegertostringinPythonPythonString|split()*argsand**kwargsinPythonPython|ProgramtoconvertStringtoaListCreateaPandasDataFramefromListsfloor()andceil()functionPythonTakingmultipleinputsfromuserinPythonGraphPlottinginPython|Set1GETandPOSTrequestsusingPythonPythonStringfind()methodFindaverageofalistinpythonStackinPythonTableofContentsAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonPythonprogramtoconvertalisttostringIterateoveralistinPythonReadafilelinebylineinPythonReadingandWritingtotextfilesinPythonPythonDictionaryPythonString|replace()Enumerate()inPythonsum()functioninPythonPrintlistsinPython(4DifferentWays)DifferentwaystocreatePandasDataframeisupper(),islower(),lower(),upper()inPythonandtheirapplicationsPython|GetalistasinputfromuserPythonListsConvertintegertostringinPythonPythonString|split()*argsand**kwargsinPythonPython|ProgramtoconvertStringtoaListCreateaPandasDataFramefromListsfloor()andceil()functionPythonTakingmultipleinputsfromuserinPythonGraphPlottinginPython|Set1GETandPOSTrequestsusingPythonPythonStringfind()methodFindaverageofalistinpythonStackinPythonImproveArticle SaveArticle LikeArticle HowtousestrptimewithmillisecondsinPythonLastUpdated: 23Aug,2021strptime()functioninpythonconvertsthestringintoDateTimeobjects.Thestrptime()isaclassmethodthattakestwoarguments: stringthatshouldbeconvertedtodatetimeobjectformatstringusedtoparsethestring.ThesetwostringargumentsaremandatoryforconvertingastringintoDateTimeobject.Syntax:strptime(date_string,format_string)ListofFormatcodes:FormatstringInterpretationExample%a Weekdayasanabbreviatedname.Sun,Mon,…,Sat %AWeekdayasfullname.Sunday,Monday,…,Saturday %wWeekdayasadecimalnumber,0isSundayand6isSaturday.0,1,…,6%dDayofthemonthasazero-paddeddecimalnumber.01,02,…,31%bMonthasanabbreviatedname.Jan,Feb,…,Dec%BMonth.January,February,…,December%mMonth01,02,…,12%yYearwithoutcentury.00,01,…,99%YYearwithcentury.0001,0002,…,2013,2014,…,9998,9999%HHour(24-hourclock).00,01,…,23%IHour(12-hourclock).01,02,…,12%peitherAMorPM.AM,PM%MMinute.00,01,…,59%SSecond.00,01,…,59%f Microsecondasadecimalnumber.000000,000001,…,999999%zUTCoffsetintheform±HHMM[SS[.ffffff]].+0000,-0400,+1030,+063415,-030712.345216%ZTimezone(UTC,GMT) %jDayoftheyear.001,002,…,366%UWeeknumberoftheyear(Sundayasthefirstdayoftheweek). 00,01,…,53%WWeeknumberoftheyear(Mondayasthefirstdayoftheweek)asadecimalnumber. 00,01,…,53%cpreferreddateandtimerepresentation.TueAug1621:30:001998%x preferreddaterepresentation.08/16/8808/16/1998%Xpreferredtimerepresentation.21:30:00%%–Aliteral‘%’character.Tousethisfunctiontoproducemillisecondsinpython%fisusedinformatcode.Givenbelowaresomeimplementations.Example1:TimewithmillisecondsPython3fromdatetimeimportdatetime  datetime_string="15/06/202113:30:15.120"  print(type(datetime_string))  format="%d/%m/%Y%H:%M:%S.%f"  #convertingdatetimestringtodatetime #objectwithmilliseconds..date_object=datetime.strptime(datetime_string,format)  print("date_object=",date_object)  #Typeisdatetimeobjectprint(type(date_object))Output: date_object=2021-06-1513:30:15.120000 Example2:timewithmillisecondsPython3fromdatetimeimportdatetime  #Gettingcurrentdatetimeandconverting#ittostringdate_str=str(datetime.now())  print(type(date_str))  print(datetime.strptime(date_str,'%Y-%m-%d%H:%M:%S.%f'))Output: 2021-08-0115:27:59.979673Example3:timewithmillisecondsPython3fromdatetimeimportdatetime  #Usingstrptime()withmilliseconds  date_time=datetime.strptime(    "17Oct202115:48:35.525001","%d%b%Y%H:%M:%S.%f")  print(date_time)Output:2021-10-1715:48:35.525001MyPersonalNotes arrow_drop_upSave LikePreviousWaybackurls-FetchalltheURLsthattheWaybackMachineknowsaboutforadomainNext ConvertdatetimestringtoYYYY-MM-DD-HH:MM:SSformatinPythonRecommendedArticlesPage:23,Aug2112,Sep2111,Dec1901,Jan2121,Oct2110,Mar2009,Feb2208,Feb1613,Oct1924,Aug1710,May2005,Jul2009,Apr1924,Jun1904,Sep1906,Dec1916,Dec1931,Dec1919,Feb2003,Mar2030,Jun2020,Jul2016,Jul2023,Jul20ArticleContributedBy:greeshmanalla@greeshmanallaVotefordifficultyEasy Normal Medium Hard ExpertArticleTags:PickedPython-datetimePythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonHowtoInstallPIPonWindows?HowtodroponeormultiplecolumnsinPandasDataframeHowToConvertPythonDictionaryToJSON?PythonClassesandObjectsPython|Pandasdataframe.groupby()MorerelatedarticlesinPythonCheckifelementexistsinlistinPythonPython-Pandasdataframe.append()Python|os.path.join()methodPython|GetuniquevaluesfromalistPythonOOPsConcepts× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?