Update Cursor skipping last row?Randomly select a record to update using arcpy.da.UpdateCursorCalculate Row if Row Value Equals Value in ListCursor update row operatorParsing Attribute TableIdentify closed polylines in ArcGIS using PythonIteratively Updating Just Bottom Row in Table using ArcPy?Comparing value with value from the next rowPython time condition within Calculate FieldArcPy rollback update / insert cursors if error occursSwitching from Nested Search Cursors to Dictionaries

On the insanity of kings as an argument against Monarchy

Manuscript was "unsubmitted" because the manuscript was deposited in Arxiv Preprints

Is it legal to have the "// (c) 2019 John Smith" header in all files when there are hundreds of contributors?

How would photo IDs work for shapeshifters?

Is it wise to focus on putting odd beats on left when playing double bass drums?

Does a dangling wire really electrocute me if I'm standing in water?

What is GPS' 19 year rollover and does it present a cybersecurity issue?

Can one use the reaction spell from the War Caster feat to cast Bigby's Hand?

Geography at the pixel level

Solve this specific large sparse system of linear equations

Is this food a bread or a loaf?

Poison Arrows Piercing damage reduced to 0, do you still get poisoned?

Shall I use personal or official e-mail account when registering to external websites for work purpose?

Why is it "Tumoren" and not "Tumore"?

In What Way Would Cryomancy Affect the Food Eaten by Medieval People?

New order #4: World

What tool would a Roman-age civilisation use to reduce/breakup silver and other metals?

Information to fellow intern about hiring?

How to make payment on the internet without leaving a money trail?

Could JWST stay at L2 "forever"?

Why can Shazam fly?

Why do we use polarized capacitors?

Is it worth rebuilding a wheel myself to save money?

Typesetting a double Over Dot on top of a symbol



Update Cursor skipping last row?


Randomly select a record to update using arcpy.da.UpdateCursorCalculate Row if Row Value Equals Value in ListCursor update row operatorParsing Attribute TableIdentify closed polylines in ArcGIS using PythonIteratively Updating Just Bottom Row in Table using ArcPy?Comparing value with value from the next rowPython time condition within Calculate FieldArcPy rollback update / insert cursors if error occursSwitching from Nested Search Cursors to Dictionaries






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have created a python function within field calculator to calculate the time difference between a timestamp (yyyy-MM-dd HH:mm:ss) in a row and the row after (the interval field in seconds). I have used a update cursor with field calculator to do this, however I am receiving null values for both the first and last row.



The first is correctly missed due to the function being reliant on having a value set by the previous row.



I am unsure as to why the last row is being skipped?



I have had this issue on several other update cursor functions including those on simple single row condition statements.



Am I missing a statement to close the update cursor loop?



My code is:



import arcpy, time, datetime
from time import strftime
from datetime import timedelta, datetime
from arcpy import da

def FindTime(table,date,interval):

firstRow = True

with arcpy.da.UpdateCursor(table, ["interval", "date"]) as cursor:

for row in cursor:
gap2 = row[2]

if firstRow == True:
gap1 = gap2
firstRow = False
continue
timedelta = gap2 - gap1
row[0] = timedelta.days * 24 * 3600 + timedelta.seconds
gap1 = gap2
cursor.updateRow(row)









share|improve this question






























    2















    I have created a python function within field calculator to calculate the time difference between a timestamp (yyyy-MM-dd HH:mm:ss) in a row and the row after (the interval field in seconds). I have used a update cursor with field calculator to do this, however I am receiving null values for both the first and last row.



    The first is correctly missed due to the function being reliant on having a value set by the previous row.



    I am unsure as to why the last row is being skipped?



    I have had this issue on several other update cursor functions including those on simple single row condition statements.



    Am I missing a statement to close the update cursor loop?



    My code is:



    import arcpy, time, datetime
    from time import strftime
    from datetime import timedelta, datetime
    from arcpy import da

    def FindTime(table,date,interval):

    firstRow = True

    with arcpy.da.UpdateCursor(table, ["interval", "date"]) as cursor:

    for row in cursor:
    gap2 = row[2]

    if firstRow == True:
    gap1 = gap2
    firstRow = False
    continue
    timedelta = gap2 - gap1
    row[0] = timedelta.days * 24 * 3600 + timedelta.seconds
    gap1 = gap2
    cursor.updateRow(row)









    share|improve this question


























      2












      2








      2


      0






      I have created a python function within field calculator to calculate the time difference between a timestamp (yyyy-MM-dd HH:mm:ss) in a row and the row after (the interval field in seconds). I have used a update cursor with field calculator to do this, however I am receiving null values for both the first and last row.



      The first is correctly missed due to the function being reliant on having a value set by the previous row.



      I am unsure as to why the last row is being skipped?



      I have had this issue on several other update cursor functions including those on simple single row condition statements.



      Am I missing a statement to close the update cursor loop?



      My code is:



      import arcpy, time, datetime
      from time import strftime
      from datetime import timedelta, datetime
      from arcpy import da

      def FindTime(table,date,interval):

      firstRow = True

      with arcpy.da.UpdateCursor(table, ["interval", "date"]) as cursor:

      for row in cursor:
      gap2 = row[2]

      if firstRow == True:
      gap1 = gap2
      firstRow = False
      continue
      timedelta = gap2 - gap1
      row[0] = timedelta.days * 24 * 3600 + timedelta.seconds
      gap1 = gap2
      cursor.updateRow(row)









      share|improve this question
















      I have created a python function within field calculator to calculate the time difference between a timestamp (yyyy-MM-dd HH:mm:ss) in a row and the row after (the interval field in seconds). I have used a update cursor with field calculator to do this, however I am receiving null values for both the first and last row.



      The first is correctly missed due to the function being reliant on having a value set by the previous row.



      I am unsure as to why the last row is being skipped?



      I have had this issue on several other update cursor functions including those on simple single row condition statements.



      Am I missing a statement to close the update cursor loop?



      My code is:



      import arcpy, time, datetime
      from time import strftime
      from datetime import timedelta, datetime
      from arcpy import da

      def FindTime(table,date,interval):

      firstRow = True

      with arcpy.da.UpdateCursor(table, ["interval", "date"]) as cursor:

      for row in cursor:
      gap2 = row[2]

      if firstRow == True:
      gap1 = gap2
      firstRow = False
      continue
      timedelta = gap2 - gap1
      row[0] = timedelta.days * 24 * 3600 + timedelta.seconds
      gap1 = gap2
      cursor.updateRow(row)






      arcpy modelbuilder field-calculator cursor python-parser






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 35 mins ago







      Will

















      asked 4 hours ago









      WillWill

      544




      544




















          1 Answer
          1






          active

          oldest

          votes


















          2














          If your field is type date, code below should work. Last line is not calculated since there is no row after. Or do you want to calculate for example second rows diff as second row-first row?



          import arcpy

          fc = 'somedates'
          datefield = 'date123'
          daydiff_field = 'seconddiff_long'

          all_dates = [i[0] for i in arcpy.da.SearchCursor(fc,datefield)]

          diff = [(d1-d0).seconds for d0,d1 in zip(all_dates, all_dates[1:])]
          givediff = iter(diff)

          with arcpy.da.UpdateCursor(fc, daydiff_field) as cursor:
          #next(cursor) #uncomment this line if you want to calculate row2 diff as row2-row1, =first row no diff
          for row in cursor:
          try:
          row[0] = next(givediff) #Fetch diffs until list is empty...
          cursor.updateRow(row)
          except StopIteration: #...then break the cursor
          break


          enter image description here






          share|improve this answer




















          • 2





            This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

            – Hornbydd
            3 hours ago






          • 2





            Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

            – BERA
            3 hours ago






          • 2





            If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

            – Berend
            43 mins ago






          • 1





            Slower than what approach?

            – BERA
            41 mins ago






          • 1





            Slower than using just an update cursor, as OP does

            – Berend
            41 mins ago











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "79"
          ;
          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: 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%2fgis.stackexchange.com%2fquestions%2f318213%2fupdate-cursor-skipping-last-row%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









          2














          If your field is type date, code below should work. Last line is not calculated since there is no row after. Or do you want to calculate for example second rows diff as second row-first row?



          import arcpy

          fc = 'somedates'
          datefield = 'date123'
          daydiff_field = 'seconddiff_long'

          all_dates = [i[0] for i in arcpy.da.SearchCursor(fc,datefield)]

          diff = [(d1-d0).seconds for d0,d1 in zip(all_dates, all_dates[1:])]
          givediff = iter(diff)

          with arcpy.da.UpdateCursor(fc, daydiff_field) as cursor:
          #next(cursor) #uncomment this line if you want to calculate row2 diff as row2-row1, =first row no diff
          for row in cursor:
          try:
          row[0] = next(givediff) #Fetch diffs until list is empty...
          cursor.updateRow(row)
          except StopIteration: #...then break the cursor
          break


          enter image description here






          share|improve this answer




















          • 2





            This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

            – Hornbydd
            3 hours ago






          • 2





            Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

            – BERA
            3 hours ago






          • 2





            If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

            – Berend
            43 mins ago






          • 1





            Slower than what approach?

            – BERA
            41 mins ago






          • 1





            Slower than using just an update cursor, as OP does

            – Berend
            41 mins ago















          2














          If your field is type date, code below should work. Last line is not calculated since there is no row after. Or do you want to calculate for example second rows diff as second row-first row?



          import arcpy

          fc = 'somedates'
          datefield = 'date123'
          daydiff_field = 'seconddiff_long'

          all_dates = [i[0] for i in arcpy.da.SearchCursor(fc,datefield)]

          diff = [(d1-d0).seconds for d0,d1 in zip(all_dates, all_dates[1:])]
          givediff = iter(diff)

          with arcpy.da.UpdateCursor(fc, daydiff_field) as cursor:
          #next(cursor) #uncomment this line if you want to calculate row2 diff as row2-row1, =first row no diff
          for row in cursor:
          try:
          row[0] = next(givediff) #Fetch diffs until list is empty...
          cursor.updateRow(row)
          except StopIteration: #...then break the cursor
          break


          enter image description here






          share|improve this answer




















          • 2





            This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

            – Hornbydd
            3 hours ago






          • 2





            Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

            – BERA
            3 hours ago






          • 2





            If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

            – Berend
            43 mins ago






          • 1





            Slower than what approach?

            – BERA
            41 mins ago






          • 1





            Slower than using just an update cursor, as OP does

            – Berend
            41 mins ago













          2












          2








          2







          If your field is type date, code below should work. Last line is not calculated since there is no row after. Or do you want to calculate for example second rows diff as second row-first row?



          import arcpy

          fc = 'somedates'
          datefield = 'date123'
          daydiff_field = 'seconddiff_long'

          all_dates = [i[0] for i in arcpy.da.SearchCursor(fc,datefield)]

          diff = [(d1-d0).seconds for d0,d1 in zip(all_dates, all_dates[1:])]
          givediff = iter(diff)

          with arcpy.da.UpdateCursor(fc, daydiff_field) as cursor:
          #next(cursor) #uncomment this line if you want to calculate row2 diff as row2-row1, =first row no diff
          for row in cursor:
          try:
          row[0] = next(givediff) #Fetch diffs until list is empty...
          cursor.updateRow(row)
          except StopIteration: #...then break the cursor
          break


          enter image description here






          share|improve this answer















          If your field is type date, code below should work. Last line is not calculated since there is no row after. Or do you want to calculate for example second rows diff as second row-first row?



          import arcpy

          fc = 'somedates'
          datefield = 'date123'
          daydiff_field = 'seconddiff_long'

          all_dates = [i[0] for i in arcpy.da.SearchCursor(fc,datefield)]

          diff = [(d1-d0).seconds for d0,d1 in zip(all_dates, all_dates[1:])]
          givediff = iter(diff)

          with arcpy.da.UpdateCursor(fc, daydiff_field) as cursor:
          #next(cursor) #uncomment this line if you want to calculate row2 diff as row2-row1, =first row no diff
          for row in cursor:
          try:
          row[0] = next(givediff) #Fetch diffs until list is empty...
          cursor.updateRow(row)
          except StopIteration: #...then break the cursor
          break


          enter image description here







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 26 mins ago

























          answered 4 hours ago









          BERABERA

          17k62044




          17k62044







          • 2





            This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

            – Hornbydd
            3 hours ago






          • 2





            Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

            – BERA
            3 hours ago






          • 2





            If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

            – Berend
            43 mins ago






          • 1





            Slower than what approach?

            – BERA
            41 mins ago






          • 1





            Slower than using just an update cursor, as OP does

            – Berend
            41 mins ago












          • 2





            This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

            – Hornbydd
            3 hours ago






          • 2





            Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

            – BERA
            3 hours ago






          • 2





            If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

            – Berend
            43 mins ago






          • 1





            Slower than what approach?

            – BERA
            41 mins ago






          • 1





            Slower than using just an update cursor, as OP does

            – Berend
            41 mins ago







          2




          2





          This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

          – Hornbydd
          3 hours ago





          This is why I love using SE, I have never used the iter() function before, had to go away and look it up, like it! Is there a performance boost using that approach or was it for convenience?

          – Hornbydd
          3 hours ago




          2




          2





          Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

          – BERA
          3 hours ago





          Nice! Dont know if there is a performance boost. I use it because it is a simple way of fetching items in a list instead of trying to iterate over a cursor and list at the same time.

          – BERA
          3 hours ago




          2




          2





          If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

          – Berend
          43 mins ago





          If anything, it will actually be slower, because the table is traversed twice instead of once. But for small tables that may not be an issue.

          – Berend
          43 mins ago




          1




          1





          Slower than what approach?

          – BERA
          41 mins ago





          Slower than what approach?

          – BERA
          41 mins ago




          1




          1





          Slower than using just an update cursor, as OP does

          – Berend
          41 mins ago





          Slower than using just an update cursor, as OP does

          – Berend
          41 mins ago

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


          • 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%2fgis.stackexchange.com%2fquestions%2f318213%2fupdate-cursor-skipping-last-row%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 should I use the fbox command correctly to avoid producing a Bad Box message?How to put a long piece of text in a box?How to specify height and width of fboxIs there an arrayrulecolor-like command to change the rule color of fbox?What is the command to highlight bad boxes in pdf?Why does fbox sometimes place the box *over* the graphic image?how to put the text in the boxHow to create command for a box where text inside the box can automatically adjust?how can I make an fbox like command with certain color, shape and width of border?how to use fbox in align modeFbox increase the spacing between the box and it content (inner margin)how to change the box height of an equationWhat is the use of the hbox in a newcommand command?

          Doxepinum Nexus interni Notae | Tabula navigationis3158DB01142WHOa682390"Structural Analysis of the Histamine H1 Receptor""Transdermal and Topical Drug Administration in the Treatment of Pain""Antidepressants as antipruritic agents: A review"

          inputenc: Unicode character … not set up for use with LaTeX The Next CEO of Stack OverflowEntering Unicode characters in LaTeXHow to solve the `Package inputenc Error: Unicode char not set up for use with LaTeX` problem?solve “Unicode char is not set up for use with LaTeX” without special handling of every new interesting UTF-8 characterPackage inputenc Error: Unicode character ² (U+B2)(inputenc) not set up for use with LaTeX. acroI2C[I²C]package inputenc error unicode char (u + 190) not set up for use with latexPackage inputenc Error: Unicode char u8:′ not set up for use with LaTeX. 3′inputenc Error: Unicode char u8: not set up for use with LaTeX with G-BriefPackage Inputenc Error: Unicode char u8: not set up for use with LaTeXPackage inputenc Error: Unicode char ́ (U+301)(inputenc) not set up for use with LaTeX. includePackage inputenc Error: Unicode char ̂ (U+302)(inputenc) not set up for use with LaTeX. … $widehatleft (OA,AA' right )$Package inputenc Error: Unicode char â„¡ (U+2121)(inputenc) not set up for use with LaTeX. printbibliography[heading=bibintoc]Package inputenc Error: Unicode char − (U+2212)(inputenc) not set up for use with LaTeXPackage inputenc Error: Unicode character α (U+3B1) not set up for use with LaTeXPackage inputenc Error: Unicode characterError: ! Package inputenc Error: Unicode char ⊘ (U+2298)(inputenc) not set up for use with LaTeX