Select to view content in your preferred language

Populate date field with any chosen date within a python script

1168
4
Jump to solution
05-08-2019 08:29 AM
RobMacDonald2
Emerging Contributor

Hi all. I am trying to write a script in Python that will populate a date field in a featureclass with a date of my choosing. Not today's date. Can anybody point me in the right direction?

Thanks!

0 Kudos
1 Solution

Accepted Solutions
FC_Basson
MVP Regular Contributor

First you need to create an expression value for the field calculation:

exp = 'datetime.datetime(2019,1,17).strftime("%Y/%m/%d")'

Then do the field calculation:

arcpy.CalculateField_management(A_OP_LISTBUILDINGS, "DateFrom",exp,"PYTHON_9.3","")

View solution in original post

4 Replies
RandyBurton
MVP Alum

You should be familiar with Python's datetime module and ArcGIS' Update Cursor tool.  For a more specific answer, you should describe your work environment.  What version of Python and ArcGIS are you using?  What is the type of geodatabase?

RobMacDonald2
Emerging Contributor

Hi Randy! Thanks very much for your answer!

I am using PyCharm 2018.3.3 and ArcGIS Pro 10.5 with a File GDB

My current attempt is:

import arcpy
import datetime

arcpy.env.workspace = r"xxxx.gdb"

arcpy.env.overwriteOutput = True

datefrom = datetime.datetime(2019,01,17)
dateto = datetime.datetime(2020,01,01)

arcpy.MakeFeatureLayer_management("L_LISTED_BUILDINGS", "LISTED_BUILDINGS")

A_OP_LISTBUILDINGS = arcpy.SelectLayerByLocation_management('LISTED_BUILDINGS', 'INTERSECT', 'FEATURE', 0, 'NEW_SELECTION')

A_OP_LISTBUILDINGS = arcpy.CalculateField_management(A_OP_LISTBUILDINGS,"DateFrom",datefrom)
A_OP_LISTBUILDINGS = arcpy.CalculateField_management(A_OP_LISTBUILDINGS,"DateTo",dateto)

arcpy.CopyFeatures_management(A_OP_LISTBUILDINGS, 'A_OP_190117_LISTBUILDINGS')

However this populates the field with "00:00:00" i.e assuming it's a time. I think this is because it is in the format yyyy,mm,dd but that is the only format datetime.datetime accepts (I think). 

Any ideas?

Many thanks

Rob

0 Kudos
FC_Basson
MVP Regular Contributor

First you need to create an expression value for the field calculation:

exp = 'datetime.datetime(2019,1,17).strftime("%Y/%m/%d")'

Then do the field calculation:

arcpy.CalculateField_management(A_OP_LISTBUILDINGS, "DateFrom",exp,"PYTHON_9.3","")
RobMacDonald2
Emerging Contributor
.strftime("%Y/%m/%d")

This was what i was missing!! Thanks so much! You legend

0 Kudos