Date conversion from POSIXct to Date in R

RDatetime

R Problem Overview


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"

R Solutions


Solution 1 - R

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

Solution 2 - R

Use the time zone parameter of as.Date:

as.Date(as.POSIXct("2013-01-01 07:00",tz="Hongkong"))
#[1] "2012-12-31"

as.Date(as.POSIXct("2013-01-01 07:00",tz="Hongkong"),tz="Hongkong")
#[1] "2013-01-01"

In fact, I recommend always using the tz parameter when using date-time converting functions. There are other nasty surprises, e.g. with daylight saving time.

Solution 3 - R

This happens as documented and previously explained when contemporaneous UTC time is before (your third example) or after midnight on your POSIXct date. To see the math for yourself, inspect as.Date.POSIXct at the console. The math under the default tz="UTC" is clear. In the non-default case, R essentially calls as.Date.POSIXlt, and the date-travel does not occur. In fact, if you had started with the lt object you would not have had this problem:

> as.Date(as.POSIXlt("2013-01-01 07:00", tz = "Hongkong"))  
[1] "2013-01-01"

The easiest work-around is to call as.Date with tz="" to force using the less offending as.Date.POSIXlt algorithm:

> as.Date(as.POSIXct("2013-01-01 07:00"), tz = "")  
[1] "2013-01-01"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlokheartView Question on Stackoverflow
Solution 1 - RalexwhanView Answer on Stackoverflow
Solution 2 - RRolandView Answer on Stackoverflow
Solution 3 - RDan MurphyView Answer on Stackoverflow