Wednesday, 12 August 2015

Using ArcGIS Desktop field calculator (python) to parse date


I'm trying to parse a datetime field using python (but have never used python for it before). I have a field that contains a valid date, but not a valid time... and other fields that have valid hour and am/pm information. I need to grab the date (mm/dd/yy) from the datetime field and then combine that with the valid hour and am/pm fields into a new string field.


Below is the vbscript way that I would do this (and it works fine, but I need to build it using python):


    (DatePart ( "m", [STARTDATE])) &"/"& 

(DatePart ("d", [STARTDATE] )) &"/"&
(DatePart ("yyyy", [STARTDATE] )) &" until "&
(DatePart ( "m", [ENDDATE])) &"/"&
(DatePart ("d", [ENDDATE] )) &"/"&
(DatePart ("yyyy", [ENDDATE] )) &" (from "&
[StartHour] &" "&
[StartAMPM] &" until "&
[EndHour] &" "&
[EndAMPM]&" )"


Here's what I've written so far using python (but doesn't work):


    def dateFull(oid)
startDateObj = datetime.datetime.strptime( !STARTDATE! , "%m/%d/%Y")
endDateObj = datetime.datetime.strptime( !ENDDATE! , "%m/%d/%Y")
return startDateObj + " to " + endDateObj + " from " + !StartHour! + " " + !StartAMPM! + " to " + !EndHour! + " " + !EndAMPM!

Can someone please help me figure out what I'm doing wrong here?



Answer



Set the python parser (don't use codeblock). I assume all input fields (!StartHour!,...) are string or date. if not bracket it with str() function


standalone python code:



startdate =  '3/1/15'
enddate = '2/15/15'

starthour = "5"
startAMPM = "PM"
endhour = "6"
endAMPM = "AM"

print str.format("{0} to {1} from {2} {3} to {4} {5}",
startdate,

enddate,
starthour,
startAMPM,
endhour,
endAMPM)

Field calculator:


str.format("{0} to {1} from {2} {3} to {4} {5}",
!startdate!,
!enddate!,

!starthour!,
!startAMPM!,
!endhour!,
!endAMPM!)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...