Convert string to datetime object in python












1















I am running the below code



import datetime
d =datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z', '%Y-%m-%d %H:%M:%S.%f')


I am getting an exception as



ValueError("time data '2018-11-20T09:12:01.7511709Z' does not match format '%Y-%m-%d %H:%M:%S.%f'",))


What is wrong with my code here. please help.










share|improve this question

























  • The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this

    – Sagar
    Nov 20 '18 at 9:47
















1















I am running the below code



import datetime
d =datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z', '%Y-%m-%d %H:%M:%S.%f')


I am getting an exception as



ValueError("time data '2018-11-20T09:12:01.7511709Z' does not match format '%Y-%m-%d %H:%M:%S.%f'",))


What is wrong with my code here. please help.










share|improve this question

























  • The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this

    – Sagar
    Nov 20 '18 at 9:47














1












1








1








I am running the below code



import datetime
d =datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z', '%Y-%m-%d %H:%M:%S.%f')


I am getting an exception as



ValueError("time data '2018-11-20T09:12:01.7511709Z' does not match format '%Y-%m-%d %H:%M:%S.%f'",))


What is wrong with my code here. please help.










share|improve this question
















I am running the below code



import datetime
d =datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z', '%Y-%m-%d %H:%M:%S.%f')


I am getting an exception as



ValueError("time data '2018-11-20T09:12:01.7511709Z' does not match format '%Y-%m-%d %H:%M:%S.%f'",))


What is wrong with my code here. please help.







python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 9:44







Sagar

















asked Nov 20 '18 at 9:39









SagarSagar

1891213




1891213













  • The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this

    – Sagar
    Nov 20 '18 at 9:47



















  • The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this

    – Sagar
    Nov 20 '18 at 9:47

















The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this

– Sagar
Nov 20 '18 at 9:47





The date comes to me as a variable which has T and Z. Its dynamic value for me. Is there a way i can convert this

– Sagar
Nov 20 '18 at 9:47












4 Answers
4






active

oldest

votes


















2














%f directive accepts from one to six digits, try omit last two digits of your input:



datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')





share|improve this answer































    2














    Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)



    The following worked fine:



    import datetime
    d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')


    If you want to correctly round your microseconds, try this:



    import datetime


    time_string = '2018-11-20T09:12:01.7511709Z'
    date_time, microseconds = time_string.split('.')
    microseconds = microseconds[:-1]
    rounding = len(microseconds) - 6
    divisor = 10 ** rounding
    new_micros = int(round(int(microseconds) / divisor, 0))
    time_string = date_time + '.' + str(new_micros) + 'Z'
    d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')





    share|improve this answer


























    • your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

      – Sagar
      Nov 20 '18 at 9:57






    • 1





      I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

      – DatHydroGuy
      Nov 20 '18 at 10:05











    • Thank you. This helps.

      – Sagar
      Nov 20 '18 at 10:30



















    0














    You can use a 3rd party library such as dateutil, which performs the microsecond truncation (though not rounding):



    from dateutil import parser

    print(parser.parse('2018-11-20T09:12:01.7511709Z'))

    datetime.datetime(2018, 11, 20, 9, 12, 1, 751170, tzinfo=tzutc())





    share|improve this answer































      0














      Also the easiest way:



      from datetime import datetime
      str(datetime.now())



      '2018-11-20 14:58:05.329281'







      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390085%2fconvert-string-to-datetime-object-in-python%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        %f directive accepts from one to six digits, try omit last two digits of your input:



        datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')





        share|improve this answer




























          2














          %f directive accepts from one to six digits, try omit last two digits of your input:



          datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')





          share|improve this answer


























            2












            2








            2







            %f directive accepts from one to six digits, try omit last two digits of your input:



            datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')





            share|improve this answer













            %f directive accepts from one to six digits, try omit last two digits of your input:



            datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 '18 at 9:47









            georgexshgeorgexsh

            10.2k11337




            10.2k11337

























                2














                Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)



                The following worked fine:



                import datetime
                d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')


                If you want to correctly round your microseconds, try this:



                import datetime


                time_string = '2018-11-20T09:12:01.7511709Z'
                date_time, microseconds = time_string.split('.')
                microseconds = microseconds[:-1]
                rounding = len(microseconds) - 6
                divisor = 10 ** rounding
                new_micros = int(round(int(microseconds) / divisor, 0))
                time_string = date_time + '.' + str(new_micros) + 'Z'
                d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')





                share|improve this answer


























                • your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

                  – Sagar
                  Nov 20 '18 at 9:57






                • 1





                  I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

                  – DatHydroGuy
                  Nov 20 '18 at 10:05











                • Thank you. This helps.

                  – Sagar
                  Nov 20 '18 at 10:30
















                2














                Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)



                The following worked fine:



                import datetime
                d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')


                If you want to correctly round your microseconds, try this:



                import datetime


                time_string = '2018-11-20T09:12:01.7511709Z'
                date_time, microseconds = time_string.split('.')
                microseconds = microseconds[:-1]
                rounding = len(microseconds) - 6
                divisor = 10 ** rounding
                new_micros = int(round(int(microseconds) / divisor, 0))
                time_string = date_time + '.' + str(new_micros) + 'Z'
                d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')





                share|improve this answer


























                • your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

                  – Sagar
                  Nov 20 '18 at 9:57






                • 1





                  I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

                  – DatHydroGuy
                  Nov 20 '18 at 10:05











                • Thank you. This helps.

                  – Sagar
                  Nov 20 '18 at 10:30














                2












                2








                2







                Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)



                The following worked fine:



                import datetime
                d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')


                If you want to correctly round your microseconds, try this:



                import datetime


                time_string = '2018-11-20T09:12:01.7511709Z'
                date_time, microseconds = time_string.split('.')
                microseconds = microseconds[:-1]
                rounding = len(microseconds) - 6
                divisor = 10 ** rounding
                new_micros = int(round(int(microseconds) / divisor, 0))
                time_string = date_time + '.' + str(new_micros) + 'Z'
                d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')





                share|improve this answer















                Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)



                The following worked fine:



                import datetime
                d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')


                If you want to correctly round your microseconds, try this:



                import datetime


                time_string = '2018-11-20T09:12:01.7511709Z'
                date_time, microseconds = time_string.split('.')
                microseconds = microseconds[:-1]
                rounding = len(microseconds) - 6
                divisor = 10 ** rounding
                new_micros = int(round(int(microseconds) / divisor, 0))
                time_string = date_time + '.' + str(new_micros) + 'Z'
                d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 20 '18 at 10:04

























                answered Nov 20 '18 at 9:46









                DatHydroGuyDatHydroGuy

                6812413




                6812413













                • your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

                  – Sagar
                  Nov 20 '18 at 9:57






                • 1





                  I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

                  – DatHydroGuy
                  Nov 20 '18 at 10:05











                • Thank you. This helps.

                  – Sagar
                  Nov 20 '18 at 10:30



















                • your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

                  – Sagar
                  Nov 20 '18 at 9:57






                • 1





                  I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

                  – DatHydroGuy
                  Nov 20 '18 at 10:05











                • Thank you. This helps.

                  – Sagar
                  Nov 20 '18 at 10:30

















                your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

                – Sagar
                Nov 20 '18 at 9:57





                your code works but you have changed the time little bit - '2018-11-20T09:12:01.7511709Z' is my time to covert. i think i may have to truncate to make this work

                – Sagar
                Nov 20 '18 at 9:57




                1




                1





                I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

                – DatHydroGuy
                Nov 20 '18 at 10:05





                I have updated the answer to extract the microseconds, correctly round them, and the re-insert them into your format string.

                – DatHydroGuy
                Nov 20 '18 at 10:05













                Thank you. This helps.

                – Sagar
                Nov 20 '18 at 10:30





                Thank you. This helps.

                – Sagar
                Nov 20 '18 at 10:30











                0














                You can use a 3rd party library such as dateutil, which performs the microsecond truncation (though not rounding):



                from dateutil import parser

                print(parser.parse('2018-11-20T09:12:01.7511709Z'))

                datetime.datetime(2018, 11, 20, 9, 12, 1, 751170, tzinfo=tzutc())





                share|improve this answer




























                  0














                  You can use a 3rd party library such as dateutil, which performs the microsecond truncation (though not rounding):



                  from dateutil import parser

                  print(parser.parse('2018-11-20T09:12:01.7511709Z'))

                  datetime.datetime(2018, 11, 20, 9, 12, 1, 751170, tzinfo=tzutc())





                  share|improve this answer


























                    0












                    0








                    0







                    You can use a 3rd party library such as dateutil, which performs the microsecond truncation (though not rounding):



                    from dateutil import parser

                    print(parser.parse('2018-11-20T09:12:01.7511709Z'))

                    datetime.datetime(2018, 11, 20, 9, 12, 1, 751170, tzinfo=tzutc())





                    share|improve this answer













                    You can use a 3rd party library such as dateutil, which performs the microsecond truncation (though not rounding):



                    from dateutil import parser

                    print(parser.parse('2018-11-20T09:12:01.7511709Z'))

                    datetime.datetime(2018, 11, 20, 9, 12, 1, 751170, tzinfo=tzutc())






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 20 '18 at 9:51









                    jppjpp

                    100k2162111




                    100k2162111























                        0














                        Also the easiest way:



                        from datetime import datetime
                        str(datetime.now())



                        '2018-11-20 14:58:05.329281'







                        share|improve this answer




























                          0














                          Also the easiest way:



                          from datetime import datetime
                          str(datetime.now())



                          '2018-11-20 14:58:05.329281'







                          share|improve this answer


























                            0












                            0








                            0







                            Also the easiest way:



                            from datetime import datetime
                            str(datetime.now())



                            '2018-11-20 14:58:05.329281'







                            share|improve this answer













                            Also the easiest way:



                            from datetime import datetime
                            str(datetime.now())



                            '2018-11-20 14:58:05.329281'








                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 20 '18 at 9:59









                            Nurislom TuraevNurislom Turaev

                            407




                            407






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390085%2fconvert-string-to-datetime-object-in-python%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to change which sound is reproduced for terminal bell?

                                Can I use Tabulator js library in my java Spring + Thymeleaf project?

                                Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents