7

I am trying to transform a date field like "00:05:40" into an integer field (i.e. 340 sec). Does anyone know how I could do that conversion please?

nmpeterson
  • 8,276
  • 33
  • 59
Paul
  • 73
  • 5

2 Answers2

11

you can use arcpy UpdateCursor function for updating your field.

Summary

The UpdateCursor function creates a cursor that lets you update or delete rows on the specified feature class, shapefile, or table. The cursor places a lock on the data that will remain until either the script completes or the update cursor object is deleted.

Syntax

UpdateCursor (dataset, {where_clause}, {spatial_reference}, {fields}, {sort_fields})

import arcpy

rows = arcpy.UpdateCursor("C:/myData.gdb/times")

for row in rows:
date = row.DATE # 00h05min40sec dat = date.split('h') hour = dat[0] # 00 min = dat[1].split('min')[0] # 05 sec = dat[1].split('min')[1].split('sec')[0] # 40 newDate = hour * 3600 + min * 60 + sec # 340 row.DATE = newDate rows.updateRow(row)

del row del rows

i hope it helps you...

urcm
  • 22,533
  • 4
  • 57
  • 109
6

If you're not comfortable with arcpy, you can also do this through the Field Calculator or Calculate Field tool. You need to turn on the Codeblock option and define a function like this:

def int_from_date(timestamp):
    hour = int(timestamp[0:2])
    min = int(timestamp[3:5])
    sec =  int(timestamp[6:8])
    time_secs = hour * 3600 + min * 60 + sec
    return time_secs

And then enter the following as the Expression (make sure the Expression Type/Parser is Python, not VB):

int_from_date(!DATE_FIELD!)
nmpeterson
  • 8,276
  • 33
  • 59
  • You were right nmpeterson, I am not really comfortable with arcpy, so I tried your solution but it keeps returning: ERROR 000539 Error running expression: int_from_date ("00:06:00") File "", line 1, in File "", line 4, in int_from_date – Paul Apr 16 '13 at 11:47
  • If you're passing it the string "00:06:00", that's the problem. You told us that the strings were in the form "00h06m00s", so the code we've provided will not handle other formats. If your data is all in the "00:06:00" format, let me know and I can alter my function. – nmpeterson Apr 16 '13 at 13:54
  • My mistake, I lead you in a wrong direction. In fact, my data is all like 00:06:45. – Paul Apr 16 '13 at 14:02
  • Ok, I decided to modify the function to use string slicing instead. Now, any string where the hours, minutes and seconds are each 2-digits, and they are all separated by one (and only one) delimiter -- "h", "m", "s", ":", or anything else -- will be a valid input. – nmpeterson Apr 16 '13 at 14:03