try: # Process: Add Field containing Image Date... gp.AddField_management(InputFC, FieldName1, "TEXT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") print "Added Field " + FieldName1 gp.addmessage("Added Field " + FieldName1) # Process: Add Field to hold sampled value... gp.AddField_management(InputFC, FieldName2, "FLOAT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") print "Added Sample Value Field" gp.addmessage("Added Field " + FieldName2) # Process: Add Field to hold Raster Path... gp.AddField_management(InputFC, FieldName3, "TEXT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "") print " Added Field containing Raster Path" gp.addmessage("Added Field " + FieldName3) objFeatures = gp.UpdateCursor(InputFC) objFeature = objFeatures.Next() while objFeature: # Calculate Image Date # DatesInterval = +DatesInterval strDate = objFeature.GetValue("Date_Time") lstDate = map(int, strDate.split("/")) objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) intDay = int(objDate.strftime("%j")) intInterval = 0 for i in range(1, 366, DatesInterval): if intDay >= i and intDay < i+DatesInterval: intInterval = i break objFeature.SetValue(FieldName1, str(intInterval)) # Calculate Raster Path objImage = "00" + str(intInterval) strTif = RasterFolder + RasterPrefix + objDate.strftime("%Y") + DatePrefix + objImage[-3:] + ".tif" objFeature.SetValue(FieldName3, strTif) objFeatures.UpdateRow(objFeature) objFeature = objFeatures.Next() del objFeature del objFeatures
lstDate = map(int, strDate.split("/")) intDay = int(objDate.strftime("%j")) objImage = "00" + strImageDate strTif = RasterFolder + RasterPrefix + objDate.strftime("%Y") + DatePrefix + objImage[-3:] + ".tif"
objFeatures = gp.UpdateCursor(InputFC):
lstDate = map(int, strDate.split(\"/\")) intDay = int(objDate.strftime(\"%j\")) objImage = \"00\" + strImageDate strTif = RasterFolder + RasterPrefix + objDate.strftime(\"%Y\") + DatePrefix + objImage[-3:] + \".tif\"
Just was hoping you could clarify a couple more things. First in the Expression I put either Calc(!Date_Time!) or Calc(!Date_Time!,!ImgDate!) ....do I put this expression because it means the code block is calculating using values from the fields Date_Time and ImgDate?
Do you mind showing me how to pass a python variable/argument from outside the codeblock. I've attached the entire code of python if that helps.
try: # Process: Add Field containing Image Date... gp.AddField_management(InputFC, FieldName1, "TEXT", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "") print "Added Field " + FieldName1 gp.addmessage("Added Field " + FieldName1) # Process: Add Field to hold sampled value... gp.AddField_management(InputFC, FieldName2, "FLOAT", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "") print "Added Sample Value Field" gp.addmessage("Added Field " + FieldName2) # Process: Add Field to hold Raster Path... gp.AddField_management(InputFC, FieldName3, "TEXT", "", "", "", "", "NON_NULLABLE", "NON_REQUIRED", "") print " Added Field containing Raster Path" gp.addmessage("Added Field " + FieldName3) objFeatures = gp.UpdateCursor(InputFC): objFeature = objFeatures.Next() while objFeature: # Calculate Image Date # DatesInterval = +DatesInterval lstDate = map(int, strDate.split(\"/\")) objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) intDay = int(objDate.strftime(\"%j\")) intInterval = 0 for i in range(1, 366, DatesInterval): if intDay >= i and intDay < i+DatesInterval: intInterval = i break objFeature.SetValue(FieldName1, intInterval) # Calculate Raster Path objImage = \"00\" + strImageDate strTif = RasterFolder + RasterPrefix + objDate.strftime(\"%Y\") + DatePrefix + objImage[-3:] + \".tif\" objFeature.SetValue(FieldName3, strTif) objFeatures.UpdateRow(objFeature) objFeature = objFeatures.Next() del objFeature del objFeatures print "Calculated ImgDate" print "Calculated NDVI Raster Path" gp.addmessage("Calculated Raster Path in " + FieldName3) # Process: Sample Rasters Listed in Fields... gp.ArcGISRasterSamplerSampleRastersInFields_GeoEco(InputFC, FieldName3, FieldName2, "", "NEAREST", "", "", "") ...etc....
import datetime def Calc(strDate): lstDate = map(int, strDate.split("/")) # create list of date integers D(D), M(M), YYYY objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) # create date object intDay = int(objDate.strftime("%j")) # integer day of the year for i in range(1, 366, 16): if intDay >= i and intDay < i+16: return i return 0
import datetime def Calc(strDate, strImageDate): lstDate = map(int, strDate.split("/")) # create list of date integers D(D), M(M), YYYY objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) # create date object objImage = "00" + strImageDate strTif = r"J:\GEOG683\HEB_NDVI_GEO" + r"\Montana_Canada_NDVI_A" + objDate.strftime("%Y") + "D" + objImage[-3:] + ".tif" return strTif
gp.CalculateField_management(InputFC, "ImgDate", "Calc(!Date_Time!)", "PYTHON", "import datetime\\ndef Calc(strDate):\\n lstDate = map(int, strDate.split(\"/\")) # create list of date integers D(D), M(M), YYYY\\n objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) # create date object\\n intDay = int(objDate.strftime(\"%j\")) # integer day of the year\\n for i in range(1, 366, 16):\\n if intDay >= i and intDay < i+16:\\n return i\\n return 0") ##print "Calculated ImgDate"
gp.CalculateField_management(InputFC, FieldName1, "Calc(!Date_Time!)", "PYTHON", "import datetime\\ndef Calc(strDate):\\n DatesInterval = +DatesInterval\\n lstDate = map(int, strDate.split(\"/\")) # create list of date integers D(D), M(M), YYYY\\n objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) # create date object\\n intDay = int(objDate.strftime(\"%j\")) # integer day of the year\\n for i in range(1, 366, DatesInterval):\\n if intDay >= i and intDay < i+DatesInterval:\\n return i\\n return 0") print "Calculated ImgDate"
Hi Brad,Thank you so much for your patience and assistance. However, I am still getting an error when I run the Calculate Field. However, now my error is:ERROR 000539: Error running expression: Calc("6/16/2006") <type 'exceptions.ValueError'>: month must be in 1..12Failed to execute (Calculate Field (3)).I think this must mean my Date_Time field isn't in the correct format. Reading the ArcGIS help online it mentions that shapefiles and coverages store Dates differently as it only stores dates and not time. In anycase my dataset is a shapefile and I'm working in 9.3.1 if that makes a difference. I apologize for not figuring this out myself, but I've having some trouble understanding the details of the code as I'm new to Python.Thanks again for you help!
lstDate = map(int, strDate.split("/")) # create list of date integers D(D), M(M), YYYY
strDate.split("/")
lstDate = map(int, ["6", "16", "2006"])
lstDate = [6, 16, 2006]
lstDate[0] = 6 # month lstDate[1] = 16 # date lstDate[2] = 2006 # year
objDate = datetime.date(lstDate[2], lstDate[1], lstDate[0]) # create date object
datetime.date(lstDate[2], lstDate[1], lstDate[0])
objDate = datetime.date(lstDate[2], lstDate[0], lstDate[1]) # create date object
import datetime def Calc(strDate, strImageDate): lstDate = map(int, strDate.split("/")) # create list of date integers D(D), M(M), YYYY objDate = datetime.date(lstDate[2], lstDate[1], lstDate[0]) # create date object strTif = r"J:\GEOG683\HED_NDVI_GEO" + r"\Montana_Canada_NDVI_A" + objDate.strftime("%Y") + "D" + strImageDate + ".tif" return strTif
import datetime def Calc(strDate, strImageDate): return r"J:\GEOG683\HED_NDVI_GEO" + r"\Montana_Canada_NDVI_A" + strDate.split("/")[2] + "D" + strImageDate + ".tif"
import datetime def Calc(strDate): lstDate = map(int, strDate.split("/")) # create list of date integers D(D), M(M), YYYY objDate = datetime.date(lstDate[2], lstDate[1], lstDate[0]) # create date object intDay = int(objDate.strftime("%j")) # integer day of the year for i in range(1, 366, 16): if intDay >= i and intDay < i+16: return i return 0
strTif = objDate.strftime("%Y") + "D" + objDate.strftime("%j") + ".tif"
dim NewString as string Select case (Right("00" + CStr(DatePart("y", [Date_Time])), 3)) case 1 to 16 NewString = "1" case 17 to 32 NewString = "17" case 33 to 48 NewString = "33" case 49 to 64 NewString = "49" case 65 to 80 NewString = "65" case 81 to 96 NewString = "81" case 97 to 112 NewString = "97" case 113 to 128 NewString = "113" case 129 to 144 NewString = "129" case 145 to 160 NewString = "145" case 161 to 176 NewString = "161" case 177 to 192 NewString = "177" case 193 to 208 NewString = "193" case 209 to 224 NewString = "209" case 225 to 240 NewString = "225" case 241 to 256 NewString = "241" case 257 to 272 NewString = "257" case 273 to 288 NewString = "273" case 289 to 304 NewString = "289" case 305 to 320 NewString = "305" case 321 to 336 NewString = "321" case 337 to 352 NewString = "337" case 353 to 367 NewString = "353" case else NewString = "Error" end select
NewString = (rstrip("00" + Str(DatePart("y", !Date_Time!)), 3)) def Calc(NewString): if NewString >= 1 or NewString <= 16: return 1 elif NewString >= 17 or NewString <=32: return 17 elif NewString >= 33 or NewString <=48: return 33 else: return 0
CStr(DatePart("yyyy", [Date_Time])) + "D" + Right("00" + CStr([ImgDate]), 3) + ".tif"
Here is a python crash course for the field calculator (assuming ArcGIS 10):First of all python is just as easy as VB (if not easier). It's just a different language, so the syntax is not identical to VB. That means that you can't write VB in python, just as you can't write C++, Perl or C# in python, so yes you need to learn a little python to write python.Second: The field calculator is actually extending the python language with the notation of "fields names" just as it did with VB. In VB field calculator you quote field names with sqaure brackets: [field_name]. In python you do the same, but with exclamation marks instead: !field_name!. That is because square brackets already have a different meaning in python.Third: String formatting in python is much more powerful than i VB, and also very different from VB. To format a string in python one creates a "format string" and then use the format operator: "This is a %s with the integer %d and the float %.4f" % ('format string', 42, 3.14159265)Fourth: To pick substring from a string, one use index and slicing: "mississippi"[0] # -> "m" "mississippi"[:4] # -> "miss" # End at the 4th character "mississippi"[-4:] # ->"ippi" # Start is 4th from the right "mississippi"[::-1] # -> "ippississim" # Stepping backwards "mississippi"[1::3] # -> "iiii" # Start at 1, and step 3 So for some field calculator examples:To copy the contents from one field to another, just quote the source field name in exclamation marks: !source_field! To copy and format floating point numbers to a text field, use a format string: "%.3f" % !source_float_field! To fill a column with the time of day, formatted in 12 hour format:First check the "Show codeblock" checkbox, then in the Pre-Logic Script Code box enter the following: import datetime t = datetime.datetime.now() Then in the calc field code box below enter the following: t.strftime('%I:%M:%S %p) # See python help for strftime for details Given a float field with POSIX timestamps (seconds since epoch). To convert that to a date and time string in ISO format (2010-01-15 06:43:12):in the pre-logic box enter: import datetime and in the calc window enter: datetime.datetime.fromtimestamp(!time_stamp_field!).strftime('%Y-%m-%d %H:%M:%S') Try these examples out and then come back with more specific questions about the Calculate Field functionallity. Also keep in mind that some people here (me included), might not be fluent in VB, so examples of what you expect specific VB code snippets to do is helpful.
"This is a %s with the integer %d and the float %.4f" % ('format string', 42, 3.14159265)
"mississippi"[0] # -> "m" "mississippi"[:4] # -> "miss" # End at the 4th character "mississippi"[-4:] # ->"ippi" # Start is 4th from the right "mississippi"[::-1] # -> "ippississim" # Stepping backwards "mississippi"[1::3] # -> "iiii" # Start at 1, and step 3
!source_field!
"%.3f" % !source_float_field!
import datetime t = datetime.datetime.now()
t.strftime('%I:%M:%S %p) # See python help for strftime for details
import datetime
datetime.datetime.fromtimestamp(!time_stamp_field!).strftime('%Y-%m-%d %H:%M:%S')
astring="08.00.00".replace('.',':') if int(astring.split(':')[0]) < 12: astring+=' AM' else: astring+=' PM'
Angemeldete Mitglieder können Beiträge verfassen, Updates folgen und mehr. Neu hier? Registriere ein kostenloses Konto.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.