Select to view content in your preferred language

Calculate Field Round to Nearest Hour

2014
4
Jump to solution
04-13-2023 08:47 AM
Labels (1)
LaurenCammack01
Occasional Contributor

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

0 Kudos
1 Solution

Accepted Solutions
jcarlson
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?

jcarlson_0-1681482251535.png

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

 

- Josh Carlson
Kendall County GIS

View solution in original post

4 Replies
DanPatterson
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...
0 Kudos
jcarlson
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.

jcarlson_0-1681402479721.png

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)
)

 

Edit to add:

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

jcarlson_1-1681402831821.png

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

jcarlson_2-1681402883185.png

 

- Josh Carlson
Kendall County GIS
LaurenCammack01
Occasional Contributor

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 t = ($feature.ReceivedDatetime)
var x = Iif (Minute(t) < 30, Hour(t), Hour(t) + 1)
if(x = 24) {
return 0 ;
} else {
return x}

0 Kudos
jcarlson
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?

jcarlson_0-1681482251535.png

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

 

- Josh Carlson
Kendall County GIS