Select to view content in your preferred language

IF statement to format/edit time

652
1
08-15-2011 03:42 PM
J__DavidKirner
New Contributor
I am looking to populate a time filed in a dataset (Field calculator) with time increments resulting in every even 30 second intervals. The current format is HH:MM:SS Where any seconds value less than 30 would be rounded down to :00 and any seconds value greater than 30 would also round down to :30. 

I.e. I want column A to become Column B
     A                       B
6:40:34 a.m. 6:40:30 a.m.
6:41:04 a.m. 6:41:00 a.m.
6:41:34 a.m. 6:41:30 a.m.
6:42:04 a.m. 6:42:00 a.m.
6:42:34 a.m. 6:42:30 a.m.
6:43:04 a.m. 6:43:00 a.m.
6:44:04 a.m. 6:44:00 a.m.
6:44:34 a.m. 6:44:30 a.m.
6:45:04 a.m. 6:45:00 a.m.


I already have a time column, but the seconds poriton of the time is not in even 30 intervals. 
How would i achieve this in field calculator?

Also I would like to know how to batch process these as well.

Thanx in advance!!
Tags (2)
0 Kudos
1 Reply
KimOllivier
Honored Contributor
If you use a cursor to read in the data you can convert the values into a Python datetime object.
That is much easier to round off and then write it out to a date field again.
Note that you have to have a featureclass that handles datetime objects which does not include dBase and hence shapefiles.

Note that rounding down is easy, just truncate the minutes and milliseconds.
Rounding up is a bit trickier because the next minute may be a whole hour, that is where the datetime object makes it easy, we create a timedelta object of one minute that will do the tricky date arithmetic for us.

In this case you want a floor function so no rounding is required.

Python: batteries included.
import datetime,math
exact = datetime.datetime.now()

newsecs = math.floor(exact.second/30.0)*30.0
newtime = exact.replace(second=newsecs,microsecond=0) 

print exact,newtime

2011-08-17 21:37:46.296000 2011-08-17 21:37:30
2011-08-17 21:37:56.562000 2011-08-17 21:37:30
2011-08-17 21:38:02.171000 2011-08-17 21:38:00
2011-08-17 21:39:35.484000 2011-08-17 21:39:30


It would be possible to create a function that could be used in the field calculator. I don't recommend that. It is much easier to debug and add extra tests to use a cursor. What if the field is Null? In a cursor you can add more tests to trap unexpected data.
0 Kudos