Reputation: 894
Why there is a strange behavior in the following expressions (why the dates are different):
today("America/New_York")
[1] "2021-02-28"
as_datetime(today("America/New_York"), tz = "America/New_York")
[1] "2021-02-27 19:00:00 EST"
Also, the local time in New York is 19:09. Is it rounding this time to get "19:00:00"?
Upvotes: 0
Views: 1500
Reputation: 33772
I think this is a consequence of using today()
, which returns a Date not a DateTime. It appears as if applying as_datetime
starts with the assumption of UTC and then substracts the time zone difference.
The output of today()
is type Date:
str(today(tzone = "America/New_York"))
Date[1:1], format: "2021-02-28"
Without time zone information, as_datetime
defaults to UTC. Without time data, it seems to assume that the time is midnight on the given date:
as_datetime(today(tzone = "America/New_York"))
[1] "2021-02-28 UTC"
str(as_datetime(today(tzone = "America/New_York")))
POSIXct[1:1], format: "2021-02-28"
So when we add time zone information it subtracts 5 hours from midnight, giving 19:00 on the previous date:
as_datetime(today(tzone = "America/New_York"), tz = "America/New_York")
[1] "2021-02-27 19:00:00 EST"
Note the different methods in as_datetime
:
showMethods("as_datetime")
Function: as_datetime (package lubridate)
x="ANY"
x="character"
x="Date"
(inherited from: x="ANY")
x="numeric"
x="POSIXt"
Upvotes: 1
Reputation: 886938
Instead of today
, use now
as_datetime(now("America/New_York"), tz = "America/New_York")
#[1] "2021-02-28 19:16:36 EST"
According to ?now
now - the current datetime as a POSIXct object
whereas today
- returns the Date
which is truncated
str(today())
#Date[1:1], format: "2021-02-28"
Upvotes: 2