1

I have a string I'm slicing and then using UpdateCursor to update rows with the outputs. The string is formatted like this:

Foo_YYYYmmddHM_Xy_Ab_Bar

I'm struggling in getting only the YYYYmmdd part of the string in a date field. My current approach is:

with arcpy.da.UpdateCursor(dataset, ["String", "Year_short","Date_date"]) as updateRows:
    for row in updateRows:
        string_split = row[0].split("_")
        row[1] = datetime.datetime.strptime(string_split[1], '%Y%m%d%H%M').year 
        row[2] = (datetime.datetime.strptime(string_split[1], '%Y%m%d%H%M')).strftime("%Y%m%d")
        updateRows.updateRow(row)

row[1] updates OK because the field is a short type, however no matter what I've tried row[2] will fail unless I include the HM component part of the date. Above is my last attempt but I have also tried the following with no success:

   row[2] = datetime.datetime.strptime(string_split[1], '%Y%m%d%H%M').date
   row[2] = datetime.datetime.strptime(string_split[1], '%Y%m%d%)
3
  • 2
    You could try using the datetime constructor datetime.datetime(Year, Month, Day) with int from a sliced string: datetime.datetime(int(string_split[1][:4]),int(string_split[1][4:6]),int(string_split[1][-2:])) provided you are absolutely sure that the dates are 8 characters in YYYYmmdd format. – Michael Stimson Feb 5 at 1:46
  • @MichaelStimson that worked perfectly, thank you. – occystrap Feb 5 at 2:10
  • 2
    That's good news. Can you please answer your own question with a snippet of your working code for future users with the same problem. – Michael Stimson Feb 5 at 2:15
1

The following worked a treat, thanks to Michael Stimson:

with arcpy.da.UpdateCursor(dataset, ["String", "Year_short","Date_date"]) as updateRows:
    for row in updateRows:
        string_split = row[0].split("_")
        row[1] = datetime.datetime.strptime(string_split[1], '%Y%m%d%H%M').year 
        row[2] = datetime.datetime(int(string_split[1][:4]),int(string_split[1][4:6]),int(string_split[1][-2:]))

Output was as expected - YYYYmmdd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.