Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a POSIX date and time (posixct) to a date relative to a timezone

I want to round a POSIXct down to the day, relative to a specific timezone.

If I try

round(as.POSIXct("2013-03-05 23:00:00 EST"), "day")

It returns

2013-03-06

Which makes sense, in that when it's 23:00:00 EST on 2013-03-05 in EST5EDT, it's already 2013-03-06 in UTC. Logically, what I want to do is:

round(as.POSIXct("2013-03-05 23:00:00 EST"), "day", tz="EST5EDT")

That is, "round this date and time to the nearest day, relative to the EST5EDT time zone". Unfortunately, round doesn't take a time zone parameter.

like image 576
loseeka Avatar asked Mar 25 '23 07:03

loseeka


1 Answers

round will round to the next day once it's past midday, which is why I think you are seeing 2013-03-06. I also have to explicitly set the tz argument in the call to as.POSIXct

Observe:

round( as.POSIXct("2013-03-05 11:00:00" , tz = "EST" ), "day" )
[1] "2013-03-05 EST"

And then once it passes noon:

round( as.POSIXct("2013-03-05 12:00:00" , tz = "EST" ), "day" )
[1] "2013-03-06 EST"

A call to format extracts the day as a character string without the tz argument. So you can get your original result without the timezone

format( round( as.POSIXct("2013-03-05 12:00:00" , tz = "EST" ), "day" ) )
[1] "2013-03-06"

If you want to round any time on that day to that day perhaps what you want instead is trunc?

format(trunc( as.POSIXct("2013-03-05 12:00:00" , tz = "EST" ), "day" ))
[1] "2013-03-05"
like image 72
Simon O'Hanlon Avatar answered Mar 26 '23 21:03

Simon O'Hanlon