Select to view content in your preferred language

# Calculate Field Round to Nearest Hour

1240
4
04-13-2023 08:47 AM
Labels (1)
New Contributor III

I'm trying to run a calculate field expression with either python or arcade that will take my date/time field and populate the nearest hour. Everything with 30 minutes and below will be rounded down and everything over 30 minutes will be rounded up. Examples below. Thank you in advance!

4/13/23 10:44:25 --> 11

4/10/23 22:26:48 --> 22

4/1/23 1:30:02 --> 2

Tags (4)
1 Solution

Accepted Solutions
by
MVP Esteemed Contributor

Ah, yeah. I didn't think about that. But if you put "24" into the hour parameter of the Date function, it automatically gives you midnight of the following day. Isn't that what you want?

Your particular error is because "=" is for assigning variables. Checking values for a conditional statement uses "==".

- Josh Carlson
Kendall County GIS
4 Replies
MVP Esteemed Contributor

some solutions here

datetime - Round time to nearest hour python - Stack Overflow

a little code block and the python parser

... sort of retired...
by
MVP Esteemed Contributor

For Arcade, there are a bunch of datetime functions already built in.

For a given timestamp, you can use Year(), Month(), Day(), Hour(), and Minute() functions to get each respective piece.

Using these values with the Date function, you can recreate the timestamp and simply adjust the hour value based on the value returned by Minute.

``````var t = Now()

return Date(
Year(t),
Month(t),
Day(t),
Iif(Minute(t) <= 30, Hour(t), Hour(t) + 1)
)``````

Here's the value run at 11:18 today.

And here it is running for 10:45. Both evaluate to 11:00!

- Josh Carlson
Kendall County GIS
New Contributor III

Thank you!! My hours are populated perfectly however I'm stuck when it is 23:45 as the hour then becomes 24. I have tried the below but am getting an parenthesis error on the if line. Any suggestions?

var x = Iif (Minute(t) < 30, Hour(t), Hour(t) + 1)
if(x = 24) {
return 0 ;
} else {
return x}

by
MVP Esteemed Contributor

Ah, yeah. I didn't think about that. But if you put "24" into the hour parameter of the Date function, it automatically gives you midnight of the following day. Isn't that what you want?

Your particular error is because "=" is for assigning variables. Checking values for a conditional statement uses "==".

- Josh Carlson
Kendall County GIS