calculate time difference in rails postgresql query











up vote
0
down vote

favorite












I need to get time difference as query result in my rails(which has Postgres database)



Brute Force Approach



I queried all items from my database and then iterating each record and then calculating time difference in hours which is very slow.



1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
2) @image_retouch_items.each do |retouch_item|
latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
end


Optimized



I need to calculate the difference of time(hours) in query itself, how to achieve that



like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')









share|improve this question


























    up vote
    0
    down vote

    favorite












    I need to get time difference as query result in my rails(which has Postgres database)



    Brute Force Approach



    I queried all items from my database and then iterating each record and then calculating time difference in hours which is very slow.



    1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
    2) @image_retouch_items.each do |retouch_item|
    latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
    end


    Optimized



    I need to calculate the difference of time(hours) in query itself, how to achieve that



    like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I need to get time difference as query result in my rails(which has Postgres database)



      Brute Force Approach



      I queried all items from my database and then iterating each record and then calculating time difference in hours which is very slow.



      1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
      2) @image_retouch_items.each do |retouch_item|
      latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
      end


      Optimized



      I need to calculate the difference of time(hours) in query itself, how to achieve that



      like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')









      share|improve this question













      I need to get time difference as query result in my rails(which has Postgres database)



      Brute Force Approach



      I queried all items from my database and then iterating each record and then calculating time difference in hours which is very slow.



      1) @image_retouch_items = ImageRetouchItem.where(:status => '0') = Retrieved all data
      2) @image_retouch_items.each do |retouch_item|
      latency_date = ((Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round
      end


      Optimized



      I need to calculate the difference of time(hours) in query itself, how to achieve that



      like - ImageRetouchItem.where(:status => '0').select('(Time.parse(DateTime.now.to_s) - Time.parse(retouch_item.created_at.to_s))/3600).round')






      ruby-on-rails postgresql ruby-on-rails-3 activerecord






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 at 13:29









      summu

      4610




      4610
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Postgres can do this for you very easily using its internal current_timestamp:



          ImageRetouchItem.where(:status => '0')
          .select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")


          current_timestamp - created_at will return an interval. By extracting epoch from that interval, we convert it to a number of seconds, which we then divide by 3600 to get hours and round using the Postgres round() function. I went ahead and casted the result as an integer using ::int, but this is optional.



          The image_retouch_item objects will now have a latency_date attribute that will contain the latency in hours, rounded to the nearest hour.






          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%2f53413130%2fcalculate-time-difference-in-rails-postgresql-query%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            Postgres can do this for you very easily using its internal current_timestamp:



            ImageRetouchItem.where(:status => '0')
            .select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")


            current_timestamp - created_at will return an interval. By extracting epoch from that interval, we convert it to a number of seconds, which we then divide by 3600 to get hours and round using the Postgres round() function. I went ahead and casted the result as an integer using ::int, but this is optional.



            The image_retouch_item objects will now have a latency_date attribute that will contain the latency in hours, rounded to the nearest hour.






            share|improve this answer



























              up vote
              1
              down vote



              accepted










              Postgres can do this for you very easily using its internal current_timestamp:



              ImageRetouchItem.where(:status => '0')
              .select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")


              current_timestamp - created_at will return an interval. By extracting epoch from that interval, we convert it to a number of seconds, which we then divide by 3600 to get hours and round using the Postgres round() function. I went ahead and casted the result as an integer using ::int, but this is optional.



              The image_retouch_item objects will now have a latency_date attribute that will contain the latency in hours, rounded to the nearest hour.






              share|improve this answer

























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                Postgres can do this for you very easily using its internal current_timestamp:



                ImageRetouchItem.where(:status => '0')
                .select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")


                current_timestamp - created_at will return an interval. By extracting epoch from that interval, we convert it to a number of seconds, which we then divide by 3600 to get hours and round using the Postgres round() function. I went ahead and casted the result as an integer using ::int, but this is optional.



                The image_retouch_item objects will now have a latency_date attribute that will contain the latency in hours, rounded to the nearest hour.






                share|improve this answer














                Postgres can do this for you very easily using its internal current_timestamp:



                ImageRetouchItem.where(:status => '0')
                .select("*, round(extract(epoch from(current_timestamp - created_at)) / 3600)::int as latency_date")


                current_timestamp - created_at will return an interval. By extracting epoch from that interval, we convert it to a number of seconds, which we then divide by 3600 to get hours and round using the Postgres round() function. I went ahead and casted the result as an integer using ::int, but this is optional.



                The image_retouch_item objects will now have a latency_date attribute that will contain the latency in hours, rounded to the nearest hour.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 21 at 15:03

























                answered Nov 21 at 14:48









                moveson

                3,6021426




                3,6021426






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413130%2fcalculate-time-difference-in-rails-postgresql-query%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

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks