2

I have a field called Abandoned Year (short integer data type) that I am trying to populate with a four digit year from a column called Decommission Date (Date data type). I have done this in the past using the DatePart( ) VB function but how do I accomplish this same task in a Python field calculation?

Here is the code written in VB:

AbandonedYear = DatePart ("YYYY", [DecommissionDate])

Thanks

RyanKDalton
23.3k19 gold badges114 silver badges180 bronze badges
asked Jun 20, 2013 at 13:38

2 Answers 2

3

Try this:

AbandonedYear = datetime.datetime.strptime( !DecommissionDate! , '%m/%d/%Y %I:%M:%S %p').year

You may need to change the format, if so a reference for those format strings is found here: Python Documentation

answered Jun 20, 2013 at 14:05
1
  • Thanks! I got this to work, datetime.datetime.strptime(!DecommissionDate!, '%m/%d/%Y').year Commented Jun 20, 2013 at 14:26
1

I built a field calculator expression using Python that behaves like that nice DatePart function in VB. I just [Load...] my *.cal file whenever I need it. Yes, I know there's much more Pythonic ways of doing this, but I just like the familiar simplicity and not having to remember that ArcGIS treats datetimes as text strings during field calculations.

def datePart( outpart, ArcGISDateField ):
 # var outpart must be one: "YYYY" | "M" | "D" | "hh" | "mm" | "ss"
 # var indatetime must take the form of either "M/D/YYYY" or "M/D/YYYY hh:mm:ss AP"
 # My Windows Date and Time settings ensure this form.
 inparts = ArcGISDateField.split(" ")
 if( len(inparts) == 1):
 inparts.extend(["00:00:00","AM"])
 inparts[0] = inparts[0].split("/")
 inparts[1] = inparts[1].split(":") 
 # build a dictionary to store the date and time parts
 outparts = {}
 outparts["M"] = int(inparts[0][0])
 outparts["D"] = int(inparts[0][1])
 outparts["YYYY"] = int(inparts[0][2])
 outparts["mm"] = int(inparts[1][1])
 outparts["ss"] = int(inparts[1][2])
 if( inparts[2] == "AM" ):
 outparts["hh"] = int(inparts[1][0])
 else:
 outparts["hh"] = int(inparts[1][0]) + 12
 # Grab and return the value of the date part I want
 return outparts[outpart]

Outfield = datePart("hh",!timestamp!)

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
answered Aug 1, 2016 at 20:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.