Convert seconds to hours/minutes/seconds and pretty print











up vote
5
down vote

favorite












I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.



import time
startTime = time.time()

#The main body of script...

print('The script finished in {0} seconds'.format(time.time() - startTime)


However this can be unhelpful if the script has been running for some time, an example output being:



'The script has been running for 4323.580279111862 seconds'


I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.



def printRuntime(seconds,finished=False):
seconds = int(seconds)
status = 'has been running for'
if finished == True:
status = 'finished in'

if seconds < 60:
print('The script {} {} seconds'.format(status,seconds))
return
elif seconds < 3600:
minutes = seconds // 60
seconds = seconds - 60*minutes
print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
return
else:
hours = seconds // 3600
minutes = (seconds - 3600*hours) // 60
seconds = seconds - 3600*hours - 60*minutes
print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
return

import time
startTime = time.time()

#The main body of script...

printRuntime(time.time() - startTime)


Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?










share|improve this question




























    up vote
    5
    down vote

    favorite












    I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.



    import time
    startTime = time.time()

    #The main body of script...

    print('The script finished in {0} seconds'.format(time.time() - startTime)


    However this can be unhelpful if the script has been running for some time, an example output being:



    'The script has been running for 4323.580279111862 seconds'


    I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.



    def printRuntime(seconds,finished=False):
    seconds = int(seconds)
    status = 'has been running for'
    if finished == True:
    status = 'finished in'

    if seconds < 60:
    print('The script {} {} seconds'.format(status,seconds))
    return
    elif seconds < 3600:
    minutes = seconds // 60
    seconds = seconds - 60*minutes
    print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
    return
    else:
    hours = seconds // 3600
    minutes = (seconds - 3600*hours) // 60
    seconds = seconds - 3600*hours - 60*minutes
    print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
    return

    import time
    startTime = time.time()

    #The main body of script...

    printRuntime(time.time() - startTime)


    Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?










    share|improve this question


























      up vote
      5
      down vote

      favorite









      up vote
      5
      down vote

      favorite











      I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.



      import time
      startTime = time.time()

      #The main body of script...

      print('The script finished in {0} seconds'.format(time.time() - startTime)


      However this can be unhelpful if the script has been running for some time, an example output being:



      'The script has been running for 4323.580279111862 seconds'


      I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.



      def printRuntime(seconds,finished=False):
      seconds = int(seconds)
      status = 'has been running for'
      if finished == True:
      status = 'finished in'

      if seconds < 60:
      print('The script {} {} seconds'.format(status,seconds))
      return
      elif seconds < 3600:
      minutes = seconds // 60
      seconds = seconds - 60*minutes
      print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
      return
      else:
      hours = seconds // 3600
      minutes = (seconds - 3600*hours) // 60
      seconds = seconds - 3600*hours - 60*minutes
      print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
      return

      import time
      startTime = time.time()

      #The main body of script...

      printRuntime(time.time() - startTime)


      Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?










      share|improve this question















      I'm self taught in python 3, and I frequently keep track of how long my scripts have been running using the time library.



      import time
      startTime = time.time()

      #The main body of script...

      print('The script finished in {0} seconds'.format(time.time() - startTime)


      However this can be unhelpful if the script has been running for some time, an example output being:



      'The script has been running for 4323.580279111862 seconds'


      I wrote a function which takes a float variable and prints the time in a more readable way. I convert the seconds to integer to get rid of the 12 decimal places, and I can pass a boolean value which changes the wording of the print to indicate that the script is still running or has finished.



      def printRuntime(seconds,finished=False):
      seconds = int(seconds)
      status = 'has been running for'
      if finished == True:
      status = 'finished in'

      if seconds < 60:
      print('The script {} {} seconds'.format(status,seconds))
      return
      elif seconds < 3600:
      minutes = seconds // 60
      seconds = seconds - 60*minutes
      print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
      return
      else:
      hours = seconds // 3600
      minutes = (seconds - 3600*hours) // 60
      seconds = seconds - 3600*hours - 60*minutes
      print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
      return

      import time
      startTime = time.time()

      #The main body of script...

      printRuntime(time.time() - startTime)


      Since I'm self taught I have no real idea about best practice. I feel like there must be a more concise way of doing this, what mistakes am I making?







      python python-3.x datetime formatting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 4 '17 at 15:52









      200_success

      127k15148410




      127k15148410










      asked Sep 4 '17 at 15:45









      Joshua Kidd

      296311




      296311






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          5
          down vote



          accepted










          There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.



          Something along these lines:



          seconds = int(seconds)
          status = 'has been running for' if not finished else 'finished in'

          minutes, seconds = divmod(seconds, 60)
          hours, minutes = divmod(minutes, 60)

          periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
          time_string = ', '.join('{} {}'.format(value, name)
          for name, value in periods
          if value)

          print('The script {} {}'.format(status, time_string))





          share|improve this answer




























            up vote
            -1
            down vote













            I am also self-taught and do it much the same as you.



            For a different reason (wanted to periodically run functions) I was looking for "time until execute" logging, anyway, I codged this together after reading several examples (including this page).



            def secs_to_dhms(seconds):
            from datetime import datetime, timedelta
            d = datetime(1,1,1) + timedelta(seconds=int(seconds))
            output = "{:02}:{:02}:{:02}:{:02}" .format(d.day-1, d.hour, d.minute, d.second)
            return output


            Not exactly what you wanted, but maybe of use to you, anyway.






            share|improve this answer








            New contributor




            Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.














            • 2




              Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
              – Toby Speight
              Nov 13 at 16:38











            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fcodereview.stackexchange.com%2fquestions%2f174796%2fconvert-seconds-to-hours-minutes-seconds-and-pretty-print%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            5
            down vote



            accepted










            There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.



            Something along these lines:



            seconds = int(seconds)
            status = 'has been running for' if not finished else 'finished in'

            minutes, seconds = divmod(seconds, 60)
            hours, minutes = divmod(minutes, 60)

            periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
            time_string = ', '.join('{} {}'.format(value, name)
            for name, value in periods
            if value)

            print('The script {} {}'.format(status, time_string))





            share|improve this answer

























              up vote
              5
              down vote



              accepted










              There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.



              Something along these lines:



              seconds = int(seconds)
              status = 'has been running for' if not finished else 'finished in'

              minutes, seconds = divmod(seconds, 60)
              hours, minutes = divmod(minutes, 60)

              periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
              time_string = ', '.join('{} {}'.format(value, name)
              for name, value in periods
              if value)

              print('The script {} {}'.format(status, time_string))





              share|improve this answer























                up vote
                5
                down vote



                accepted







                up vote
                5
                down vote



                accepted






                There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.



                Something along these lines:



                seconds = int(seconds)
                status = 'has been running for' if not finished else 'finished in'

                minutes, seconds = divmod(seconds, 60)
                hours, minutes = divmod(minutes, 60)

                periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
                time_string = ', '.join('{} {}'.format(value, name)
                for name, value in periods
                if value)

                print('The script {} {}'.format(status, time_string))





                share|improve this answer












                There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.



                Something along these lines:



                seconds = int(seconds)
                status = 'has been running for' if not finished else 'finished in'

                minutes, seconds = divmod(seconds, 60)
                hours, minutes = divmod(minutes, 60)

                periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
                time_string = ', '.join('{} {}'.format(value, name)
                for name, value in periods
                if value)

                print('The script {} {}'.format(status, time_string))






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Sep 4 '17 at 16:09









                alecxe

                14.4k53176




                14.4k53176
























                    up vote
                    -1
                    down vote













                    I am also self-taught and do it much the same as you.



                    For a different reason (wanted to periodically run functions) I was looking for "time until execute" logging, anyway, I codged this together after reading several examples (including this page).



                    def secs_to_dhms(seconds):
                    from datetime import datetime, timedelta
                    d = datetime(1,1,1) + timedelta(seconds=int(seconds))
                    output = "{:02}:{:02}:{:02}:{:02}" .format(d.day-1, d.hour, d.minute, d.second)
                    return output


                    Not exactly what you wanted, but maybe of use to you, anyway.






                    share|improve this answer








                    New contributor




                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.














                    • 2




                      Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
                      – Toby Speight
                      Nov 13 at 16:38















                    up vote
                    -1
                    down vote













                    I am also self-taught and do it much the same as you.



                    For a different reason (wanted to periodically run functions) I was looking for "time until execute" logging, anyway, I codged this together after reading several examples (including this page).



                    def secs_to_dhms(seconds):
                    from datetime import datetime, timedelta
                    d = datetime(1,1,1) + timedelta(seconds=int(seconds))
                    output = "{:02}:{:02}:{:02}:{:02}" .format(d.day-1, d.hour, d.minute, d.second)
                    return output


                    Not exactly what you wanted, but maybe of use to you, anyway.






                    share|improve this answer








                    New contributor




                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.














                    • 2




                      Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
                      – Toby Speight
                      Nov 13 at 16:38













                    up vote
                    -1
                    down vote










                    up vote
                    -1
                    down vote









                    I am also self-taught and do it much the same as you.



                    For a different reason (wanted to periodically run functions) I was looking for "time until execute" logging, anyway, I codged this together after reading several examples (including this page).



                    def secs_to_dhms(seconds):
                    from datetime import datetime, timedelta
                    d = datetime(1,1,1) + timedelta(seconds=int(seconds))
                    output = "{:02}:{:02}:{:02}:{:02}" .format(d.day-1, d.hour, d.minute, d.second)
                    return output


                    Not exactly what you wanted, but maybe of use to you, anyway.






                    share|improve this answer








                    New contributor




                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    I am also self-taught and do it much the same as you.



                    For a different reason (wanted to periodically run functions) I was looking for "time until execute" logging, anyway, I codged this together after reading several examples (including this page).



                    def secs_to_dhms(seconds):
                    from datetime import datetime, timedelta
                    d = datetime(1,1,1) + timedelta(seconds=int(seconds))
                    output = "{:02}:{:02}:{:02}:{:02}" .format(d.day-1, d.hour, d.minute, d.second)
                    return output


                    Not exactly what you wanted, but maybe of use to you, anyway.







                    share|improve this answer








                    New contributor




                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    share|improve this answer



                    share|improve this answer






                    New contributor




                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    answered Nov 13 at 14:10









                    Johan

                    1




                    1




                    New contributor




                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.





                    New contributor





                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.






                    Johan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.








                    • 2




                      Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
                      – Toby Speight
                      Nov 13 at 16:38














                    • 2




                      Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
                      – Toby Speight
                      Nov 13 at 16:38








                    2




                    2




                    Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
                    – Toby Speight
                    Nov 13 at 16:38




                    Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please edit to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading How to Answer.
                    – Toby Speight
                    Nov 13 at 16:38


















                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f174796%2fconvert-seconds-to-hours-minutes-seconds-and-pretty-print%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

                    Сан-Квентин

                    Алькесар

                    Josef Freinademetz