Advertisement
Guest User

Untitled

a guest
Nov 1st, 2014
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.45 KB | None | 0 0
  1. # ---------------------------------------------------------------------------
  2. #
  3. # Created on: Sept 9, 2010
  4. # Created by: The Nature Conservancy
  5. # Calculates delta time (hours) between successive rows based on timestamp field
  6. #
  7. # Credit should go to Richard Crissup, ESRI DTC, Washington DC for his
  8. # 6-27-2008 date_diff.py posted as an ArcScript
  9. '''
  10. This script assumes the format "month/day/year hours:minutes:seconds".
  11. The hour needs to be in military time.
  12. If you are using another format please alter the script accordingly.
  13. I do a little checking to see if the input string is in the format
  14. "month/day/year hours:minutes:seconds" as this is a common date time
  15. format. Also the hours:minute:seconds is included, otherwise we could
  16. be off by almost a day.
  17.  
  18. I am not sure if the time functions do any conversion to GMT,
  19. so if the times passed in are in another time zone than the computer
  20. running the script, you will need to pad the time given back in
  21. seconds by the difference in time from where the computer is in relation
  22. to where they were collected.
  23.  
  24. '''
  25. # ---------------------------------------------------------------------------
  26. # FUNCTIONS
  27. #----------------------------------------------------------------------------
  28. import arcgisscripting, sys, os, re
  29. import time, calendar, string, decimal
  30. def func_check_format(time_string):
  31. if time_string.find("/") == -1:
  32. print "Error: time string doesn't contain any '/' expected format
  33. is month/day/year hour:minutes:seconds"
  34. elif time_string.find(":") == -1:
  35. print "Error: time string doesn't contain any ':' expected format
  36. is month/day/year hour:minutes:seconds"
  37.  
  38. list = time_string.split()
  39. if (len(list)) <> 2:
  40. print "Error time string doesn't contain and date and time separated
  41. by a space. Expected format is 'month/day/year hour:minutes:seconds'"
  42.  
  43.  
  44. def func_parse_time(time_string):
  45. '''
  46. take the time value and make it into a tuple with 9 values
  47. example = "2004/03/01 23:50:00". If the date values don't look like this
  48. then the script will fail.
  49. '''
  50. year=0;month=0;day=0;hour=0;minute=0;sec=0;
  51. time_string = str(time_string)
  52. l=time_string.split()
  53. if not len(l) == 2:
  54. gp.AddError("Error: func_parse_time, expected 2 items in list l got" +
  55. str(len(l)) + "time field value = " + time_string)
  56. raise Exception
  57. cal=l[0];cal=cal.split("/")
  58. if not len(cal) == 3:
  59. gp.AddError("Error: func_parse_time, expected 3 items in list cal got " +
  60. str(len(cal)) + "time field value = " + time_string)
  61. raise Exception
  62. ti=l[1];ti=ti.split(":")
  63. if not len(ti) == 3:
  64. gp.AddError("Error: func_parse_time, expected 3 items in list ti got " +
  65. str(len(ti)) + "time field value = " + time_string)
  66. raise Exception
  67. if int(len(cal[0]))== 4:
  68. year=int(cal[0])
  69. month=int(cal[1])
  70. day=int(cal[2])
  71. else:
  72. year=int(cal[2])
  73. month=int(cal[0])
  74. day=int(cal[1])
  75. hour=int(ti[0])
  76. minute=int(ti[1])
  77. sec=int(ti[2])
  78. # formated tuple to match input for time functions
  79. result=(year,month,day,hour,minute,sec,0,0,0)
  80. return result
  81.  
  82.  
  83. #----------------------------------------------------------------------------
  84.  
  85. def func_time_diff(start_t,end_t):
  86. '''
  87. Take the two numbers that represent seconds
  88. since Jan 1 1970 and return the difference of
  89. those two numbers in hours. There are 3600 seconds
  90. in an hour. 60 secs * 60 min '''
  91.  
  92. start_secs = calendar.timegm(start_t)
  93. end_secs = calendar.timegm(end_t)
  94.  
  95. x=abs(end_secs - start_secs)
  96. #diff = number hours difference
  97. #as ((x/60)/60)
  98. diff = float(x)/float(3600)
  99. return diff
  100.  
  101. #----------------------------------------------------------------------------
  102.  
  103. print "Executing getnextLTIME.py script..."
  104.  
  105. try:
  106. gp = arcgisscripting.create(9.3)
  107.  
  108. # set parameter to what user drags in
  109. fcdrag = gp.GetParameterAsText(0)
  110. psplit = os.path.split(fcdrag)
  111.  
  112. folder = str(psplit[0]) #containing folder
  113. fc = str(psplit[1]) #feature class
  114. fullpath = str(fcdrag)
  115.  
  116. gp.Workspace = folder
  117.  
  118. fldA = gp.GetParameterAsText(1) # Timestamp field
  119. fldDiff = gp.GetParameterAsText(2) # Hours field
  120.  
  121. # set the toolbox for adding the field to data managment
  122. gp.Toolbox = "management"
  123. # add the user named hours field to the feature class
  124. gp.addfield (fc,fldDiff,"double")
  125. #gp.addindex(fc,fldA,"indA","NON_UNIQUE", "ASCENDING")
  126.  
  127. desc = gp.describe(fullpath)
  128. updateCursor = gp.UpdateCursor(fullpath, "", desc.SpatialReference,
  129. fldA+"; "+ fldDiff, fldA)
  130. row = updateCursor.Next()
  131. count = 0
  132. oldtime = str(row.GetValue(fldA))
  133. #check datetime to see if parseable
  134. func_check_format(oldtime)
  135. gp.addmessage("Calculating " + fldDiff + " field...")
  136.  
  137. while row <> None:
  138. if count == 0:
  139. row.SetValue(fldDiff, 0)
  140. else:
  141. start_t = func_parse_time(oldtime)
  142. b = str(row.GetValue(fldA))
  143. end_t = func_parse_time(b)
  144. diff_hrs = func_time_diff(start_t, end_t)
  145. row.SetValue(fldDiff, diff_hrs)
  146. oldtime = b
  147.  
  148. count += 1
  149. updateCursor.UpdateRow(row)
  150. row = updateCursor.Next()
  151.  
  152. gp.addmessage("Updated " +str(count+1)+ " rows.")
  153. #gp.removeindex(fc,"indA")
  154. del updateCursor
  155. del row
  156.  
  157. except Exception, ErrDesc:
  158. import traceback;traceback.print_exc()
  159.  
  160. print "Script complete."
  161.  
  162. import arcgisscripting
  163. gp = arcgisscripting.create(9.3)
  164.  
  165. # Create a code block to be executed for each row in the table
  166. # The code block is necessary for anything over a one-liner.
  167. codeblock = """
  168. import datetime
  169. class CalcDiff(object):
  170. # Class attributes are static, that is, only one exists for all
  171. # instances, kind of like a global variable for classes.
  172. Last = None
  173. def calcDiff(self,timestring):
  174. # parse the time string according to our format.
  175. t = datetime.datetime.strptime(timestring, '%m/%d/%Y %H:%M:%S')
  176. # return the difference from the last date/time
  177. if CalcDiff.Last:
  178. diff = t - CalcDiff.Last
  179. else:
  180. diff = datetime.timedelta()
  181. CalcDiff.Last = t
  182. return float(diff.seconds)/3600.0
  183. """
  184.  
  185. expression = """CalcDiff().calcDiff(!timelabel!)"""
  186.  
  187. gp.CalculateField_management(r'c:workspacetest.gdbtest','timediff',expression, "PYTHON", codeblock)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement