How to convert string contains datetime in isoformat to date and time values?











up vote
-1
down vote

favorite












I have the following string format (Python 3.6):



'2018-11-19T10:04:57.426872'


I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'



I tried to convert it with:



from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')


But this gives:



ValueError: unconverted data remains: T10:04:57.426872


In the above example I want to see:



start_date = '2018-11-19'
start_time = '10:04'









share|improve this question
























  • The pattern you give as an argument to strptime must cover the whole string, otherwise it is unclear where those info is in the string. Als for extracting hours and minutes: if your pattern would work, would it extract 10:04 or 04:57?
    – Christian König
    Nov 19 at 12:00












  • @ChristianKönig When I do: print datetime.datetime.utcnow().isoformat() I get: 2018-11-19T12:01:54.579000 and when I do print datetime.datetime.utcnow() I get 2018-11-19 12:01:54.579000 so the start_time in this case should be 12:01
    – Luis
    Nov 19 at 12:04

















up vote
-1
down vote

favorite












I have the following string format (Python 3.6):



'2018-11-19T10:04:57.426872'


I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'



I tried to convert it with:



from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')


But this gives:



ValueError: unconverted data remains: T10:04:57.426872


In the above example I want to see:



start_date = '2018-11-19'
start_time = '10:04'









share|improve this question
























  • The pattern you give as an argument to strptime must cover the whole string, otherwise it is unclear where those info is in the string. Als for extracting hours and minutes: if your pattern would work, would it extract 10:04 or 04:57?
    – Christian König
    Nov 19 at 12:00












  • @ChristianKönig When I do: print datetime.datetime.utcnow().isoformat() I get: 2018-11-19T12:01:54.579000 and when I do print datetime.datetime.utcnow() I get 2018-11-19 12:01:54.579000 so the start_time in this case should be 12:01
    – Luis
    Nov 19 at 12:04















up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I have the following string format (Python 3.6):



'2018-11-19T10:04:57.426872'


I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'



I tried to convert it with:



from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')


But this gives:



ValueError: unconverted data remains: T10:04:57.426872


In the above example I want to see:



start_date = '2018-11-19'
start_time = '10:04'









share|improve this question















I have the following string format (Python 3.6):



'2018-11-19T10:04:57.426872'


I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'



I tried to convert it with:



from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')


But this gives:



ValueError: unconverted data remains: T10:04:57.426872


In the above example I want to see:



start_date = '2018-11-19'
start_time = '10:04'






python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 12:05

























asked Nov 19 at 11:53









Luis

177




177












  • The pattern you give as an argument to strptime must cover the whole string, otherwise it is unclear where those info is in the string. Als for extracting hours and minutes: if your pattern would work, would it extract 10:04 or 04:57?
    – Christian König
    Nov 19 at 12:00












  • @ChristianKönig When I do: print datetime.datetime.utcnow().isoformat() I get: 2018-11-19T12:01:54.579000 and when I do print datetime.datetime.utcnow() I get 2018-11-19 12:01:54.579000 so the start_time in this case should be 12:01
    – Luis
    Nov 19 at 12:04




















  • The pattern you give as an argument to strptime must cover the whole string, otherwise it is unclear where those info is in the string. Als for extracting hours and minutes: if your pattern would work, would it extract 10:04 or 04:57?
    – Christian König
    Nov 19 at 12:00












  • @ChristianKönig When I do: print datetime.datetime.utcnow().isoformat() I get: 2018-11-19T12:01:54.579000 and when I do print datetime.datetime.utcnow() I get 2018-11-19 12:01:54.579000 so the start_time in this case should be 12:01
    – Luis
    Nov 19 at 12:04


















The pattern you give as an argument to strptime must cover the whole string, otherwise it is unclear where those info is in the string. Als for extracting hours and minutes: if your pattern would work, would it extract 10:04 or 04:57?
– Christian König
Nov 19 at 12:00






The pattern you give as an argument to strptime must cover the whole string, otherwise it is unclear where those info is in the string. Als for extracting hours and minutes: if your pattern would work, would it extract 10:04 or 04:57?
– Christian König
Nov 19 at 12:00














@ChristianKönig When I do: print datetime.datetime.utcnow().isoformat() I get: 2018-11-19T12:01:54.579000 and when I do print datetime.datetime.utcnow() I get 2018-11-19 12:01:54.579000 so the start_time in this case should be 12:01
– Luis
Nov 19 at 12:04






@ChristianKönig When I do: print datetime.datetime.utcnow().isoformat() I get: 2018-11-19T12:01:54.579000 and when I do print datetime.datetime.utcnow() I get 2018-11-19 12:01:54.579000 so the start_time in this case should be 12:01
– Luis
Nov 19 at 12:04














3 Answers
3






active

oldest

votes

















up vote
1
down vote



accepted










Since the date seems to be in ISO-Format, a simple



start = datetime.datetime.fromisoformat(text)


will parse it correctly. From there you can get your date and time with



start_date = start.strftime("%Y-%m-%d")
start_time = start.strftime("%H:%M")


Edit:



For Python < 3.7, you can use this format:



start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")


For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.






share|improve this answer























  • AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
    – Luis
    Nov 19 at 12:10










  • @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
    – toti08
    Nov 19 at 12:20










  • Ah, you're right - New in version 3.7. Will edit.
    – Christian König
    Nov 19 at 12:20










  • @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
    – Luis
    Nov 19 at 12:22










  • @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
    – Luis
    Nov 19 at 12:24




















up vote
0
down vote













You need to parse the entire string into one datetime object and then extract your required values from that.



dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
d = dt.date()
t = dt.time()
print(d.strftime('%Y-%m-%d'))
print(t.strftime('%H:%M'))


Which outputs:



2018-11-19
10:04





share|improve this answer




























    up vote
    0
    down vote













    Try this:We have one of the best package for parsing dates called dateutil.



    from dateutil import parser
    date1='2018-11-19T10:04:57.426872'
    print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
    print 'Start_time:',parser.parse(date1).strftime("%H:%M")

    Result:Start_date:2018-11-19
    Start_time:10:04





    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',
      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%2f53374085%2fhow-to-convert-string-contains-datetime-in-isoformat-to-date-and-time-values%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote



      accepted










      Since the date seems to be in ISO-Format, a simple



      start = datetime.datetime.fromisoformat(text)


      will parse it correctly. From there you can get your date and time with



      start_date = start.strftime("%Y-%m-%d")
      start_time = start.strftime("%H:%M")


      Edit:



      For Python < 3.7, you can use this format:



      start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")


      For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.






      share|improve this answer























      • AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
        – Luis
        Nov 19 at 12:10










      • @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
        – toti08
        Nov 19 at 12:20










      • Ah, you're right - New in version 3.7. Will edit.
        – Christian König
        Nov 19 at 12:20










      • @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
        – Luis
        Nov 19 at 12:22










      • @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
        – Luis
        Nov 19 at 12:24

















      up vote
      1
      down vote



      accepted










      Since the date seems to be in ISO-Format, a simple



      start = datetime.datetime.fromisoformat(text)


      will parse it correctly. From there you can get your date and time with



      start_date = start.strftime("%Y-%m-%d")
      start_time = start.strftime("%H:%M")


      Edit:



      For Python < 3.7, you can use this format:



      start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")


      For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.






      share|improve this answer























      • AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
        – Luis
        Nov 19 at 12:10










      • @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
        – toti08
        Nov 19 at 12:20










      • Ah, you're right - New in version 3.7. Will edit.
        – Christian König
        Nov 19 at 12:20










      • @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
        – Luis
        Nov 19 at 12:22










      • @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
        – Luis
        Nov 19 at 12:24















      up vote
      1
      down vote



      accepted







      up vote
      1
      down vote



      accepted






      Since the date seems to be in ISO-Format, a simple



      start = datetime.datetime.fromisoformat(text)


      will parse it correctly. From there you can get your date and time with



      start_date = start.strftime("%Y-%m-%d")
      start_time = start.strftime("%H:%M")


      Edit:



      For Python < 3.7, you can use this format:



      start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")


      For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.






      share|improve this answer














      Since the date seems to be in ISO-Format, a simple



      start = datetime.datetime.fromisoformat(text)


      will parse it correctly. From there you can get your date and time with



      start_date = start.strftime("%Y-%m-%d")
      start_time = start.strftime("%H:%M")


      Edit:



      For Python < 3.7, you can use this format:



      start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")


      For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 19 at 12:25

























      answered Nov 19 at 12:03









      Christian König

      2,416918




      2,416918












      • AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
        – Luis
        Nov 19 at 12:10










      • @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
        – toti08
        Nov 19 at 12:20










      • Ah, you're right - New in version 3.7. Will edit.
        – Christian König
        Nov 19 at 12:20










      • @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
        – Luis
        Nov 19 at 12:22










      • @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
        – Luis
        Nov 19 at 12:24




















      • AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
        – Luis
        Nov 19 at 12:10










      • @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
        – toti08
        Nov 19 at 12:20










      • Ah, you're right - New in version 3.7. Will edit.
        – Christian König
        Nov 19 at 12:20










      • @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
        – Luis
        Nov 19 at 12:22










      • @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
        – Luis
        Nov 19 at 12:24


















      AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
      – Luis
      Nov 19 at 12:10




      AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
      – Luis
      Nov 19 at 12:10












      @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
      – toti08
      Nov 19 at 12:20




      @Luis just remove one datetime so you read start = datetime.fromisoformat(text)
      – toti08
      Nov 19 at 12:20












      Ah, you're right - New in version 3.7. Will edit.
      – Christian König
      Nov 19 at 12:20




      Ah, you're right - New in version 3.7. Will edit.
      – Christian König
      Nov 19 at 12:20












      @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
      – Luis
      Nov 19 at 12:22




      @toti08 already did that. The error is after I removed the redundant datetime. I think this function is introduced in Python 3.7 I run Python 3.6
      – Luis
      Nov 19 at 12:22












      @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
      – Luis
      Nov 19 at 12:24






      @toti08 I tried datetime.datetime.fromisoformat(start_timestamp) and also datetime.fromisoformat(start_timestamp) It's the same error. This function isn't available for Python 3.6
      – Luis
      Nov 19 at 12:24














      up vote
      0
      down vote













      You need to parse the entire string into one datetime object and then extract your required values from that.



      dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
      d = dt.date()
      t = dt.time()
      print(d.strftime('%Y-%m-%d'))
      print(t.strftime('%H:%M'))


      Which outputs:



      2018-11-19
      10:04





      share|improve this answer

























        up vote
        0
        down vote













        You need to parse the entire string into one datetime object and then extract your required values from that.



        dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
        d = dt.date()
        t = dt.time()
        print(d.strftime('%Y-%m-%d'))
        print(t.strftime('%H:%M'))


        Which outputs:



        2018-11-19
        10:04





        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          You need to parse the entire string into one datetime object and then extract your required values from that.



          dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
          d = dt.date()
          t = dt.time()
          print(d.strftime('%Y-%m-%d'))
          print(t.strftime('%H:%M'))


          Which outputs:



          2018-11-19
          10:04





          share|improve this answer












          You need to parse the entire string into one datetime object and then extract your required values from that.



          dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
          d = dt.date()
          t = dt.time()
          print(d.strftime('%Y-%m-%d'))
          print(t.strftime('%H:%M'))


          Which outputs:



          2018-11-19
          10:04






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 at 12:02









          Vikrant Sharma

          29816




          29816






















              up vote
              0
              down vote













              Try this:We have one of the best package for parsing dates called dateutil.



              from dateutil import parser
              date1='2018-11-19T10:04:57.426872'
              print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
              print 'Start_time:',parser.parse(date1).strftime("%H:%M")

              Result:Start_date:2018-11-19
              Start_time:10:04





              share|improve this answer

























                up vote
                0
                down vote













                Try this:We have one of the best package for parsing dates called dateutil.



                from dateutil import parser
                date1='2018-11-19T10:04:57.426872'
                print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
                print 'Start_time:',parser.parse(date1).strftime("%H:%M")

                Result:Start_date:2018-11-19
                Start_time:10:04





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Try this:We have one of the best package for parsing dates called dateutil.



                  from dateutil import parser
                  date1='2018-11-19T10:04:57.426872'
                  print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
                  print 'Start_time:',parser.parse(date1).strftime("%H:%M")

                  Result:Start_date:2018-11-19
                  Start_time:10:04





                  share|improve this answer












                  Try this:We have one of the best package for parsing dates called dateutil.



                  from dateutil import parser
                  date1='2018-11-19T10:04:57.426872'
                  print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
                  print 'Start_time:',parser.parse(date1).strftime("%H:%M")

                  Result:Start_date:2018-11-19
                  Start_time:10:04






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 19 at 12:26









                  Narendra Lucky

                  568




                  568






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53374085%2fhow-to-convert-string-contains-datetime-in-isoformat-to-date-and-time-values%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

                      Wiesbaden

                      Marschland

                      Dieringhausen