Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

datetime - Date conversion from POSIXct to Date in R

can anyone tell me why R give such outcome below:

> as.POSIXct("2013-01-01 08:00")
[1] "2013-01-01 08:00:00 HKT"
> as.Date(as.POSIXct("2013-01-01 08:00"))
[1] "2013-01-01"
> as.POSIXct("2013-01-01 07:00")
[1] "2013-01-01 07:00:00 HKT"
> as.Date(as.POSIXct("2013-01-01 07:00"))
[1] "2012-12-31"

Shouldn't it be 2013-01-01 after converting POSIXct to Date for 2013-01-01 07:00, is there any way to change the cutoff from 08:00 to 00:00?

Update #1

I found the following can fix my problem, but in a less neat way

> as.Date(as.character(as.POSIXct("2013-01-01 07:00")))
[1] "2013-01-01"
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The problem here is timezones - you can see you're in "HKT". Try:

as.Date(as.POSIXct("2013-01-01 07:00", 'GMT'))
[1] "2013-01-01"

From ?as.Date():

["POSIXct" is] converted to days by ignoring the time after midnight in the representation of the time in specified timezone, default UTC


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...