[GIS] Converting ArcGIS date value to string reading in mm/dd/yyyy format using ArcPy

arcgis-10.0arcgis-desktoparcpydatefile-geodatabase

I am writing an arcpy tool script in ArcGIS 10.0. In a fGDB feature class, I have a Date type field. I gather that the values in the Date field are stored as long integer dates, but they display in mm/dd/yyy format in the table. What I want to do is capture the integer date value as a string showing the date in mm/dd/yyyy format. How do I go about this?

There are many examples of how to convert a date/time string to a date object/value but not vice versa. I am appending features from a feature class with many fields, including a date field, into a standard-schema fc (which I can't change) that has few fields. To save a lot of the technical attributes in the input, I must dump it all into a catch-all, user-controlled text field that is defined in the target. The date data from the input is one of those pieces of data I need to save, hence the need to convert the date to a string.

There is likely a fairly easy solution I'm missing, but at the moment I am at a loss. I appreciate any help that comes my way.

Best Answer

GP cursors read date values as datetime objects, so you can use datetime.strftime() to format it as you like, or datetime.ctime() to format it as the default format (%a %b %d %H:%M:%S %Y).

Here's an example using mm/dd/yyyy:

import arcpy
from datetime import datetime
fc = r"C:\GISData\test.gdb\atlantic_hurricanes_2000"
rows = arcpy.SearchCursor(fc)
for row in rows:
    datetimeVal = row.getValue("Date_Time")
    formattedTime = datetime.strftime(datetimeVal, "%m/%d/%Y")
    print formattedTime

For the meanings of the various time formatting codes see strftime behavior.