Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I try to coerce a POSIXct date-time to a Date using as.Date, it seems to return wrong date.

I suspect it has got something to do with the time zone. I tried the tz argument in as.Date, but it didn't give the expected date.

# POSIXct returns day of month 24  
data$Time[3]
# [1] "2020-03-24 00:02:00 IST"

class(data$Time[3])
# [1] "POSIXct" "POSIXt"

# coerce to Date, returns 23 
as.Date(data$Time[3])
# [1] "2020-03-23"

# try the time zone argument, without luck
as.Date(data$Time[3], tz = "IST")
# [1] "2020-03-23"
# Warning message:
# In as.POSIXlt.POSIXct(x, tz = tz) : unknown timezone 'IST' 

Sys.timezone()
# [1] "Asia/Calcutta"

Any ideas what may be going wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
600 views
Welcome To Ask or Share your Answers For Others

1 Answer

The clue is in the warning message. as.Date() doesn't know how to interpret IST as a timezone and so defaults to UTC. Assuming that IST is Indian Standard Time (rather than Irish Standard time) and that IST is UTC+5:30, as.Date() is giving the expected result, even if it is incorrect for your purposes.

Providing a date with a timezone expressed as an offset from UTC gives the desired result.

as.Date("2020-03-24 00:02:00 UTC+5:30")
[1] "2020-03-24"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...