Select to view content in your preferred language

How to calculate date field in python script - formatting question

17743
10
02-11-2011 11:10 AM
jduval
by
Emerging Contributor
I am trying to calculate a DATE field on a feature class in a personal geodatabase.  I have a date variable that is a string: distDate = "2011-02-11"

I am not able to figure out the proper formatting to get it to work in a python script.  This is what I have, but it does not update with this date, nor does it error out.  In ArcMap, I can use calculate field on the attribute table and successfully update the date with #2011-02-11# (VB).

arcpy.CalculateField_management (inFC, "DistDate", "#"+distDate+"#")

I could not find help on the ESRI support site, nor by just googling it.  Does anybody have suggestions?

Julie
GISP
Tags (2)
0 Kudos
10 Replies
KristinaGrace
Deactivated User
# Import modules
import arcpy
from datetime import datetime

# Define variables
surveyDateEnteredFld = "DATENTERED" # existing text field
surveyDateFld = "SURVEY_DATE"
expression = "formatDate(!" + surveyDateEnteredFld + "!)"
codeBlock = """def formatDate(datestr):
        d = datetime.datetime.strptime(datestr, '%m%d%Y')
        return d"""

# Add and calculate new date field
arcpy.AddField_management(outputTableView, surveyDateFld, "DATE")
arcpy.CalculateField_management(outputTableView, surveyDateFld, expression, "PYTHON", codeBlock)
0 Kudos