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
?
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"
To get the year from a date in R you can use the functions as. POSIXct() and format() . For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") .
To convert Date to Numeric format in R, use the as. POSIXct() function and then you can coerce it to a numeric value using as. numeric() function.
You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.
The dates are converted to the standard time zone, UTC. A string type date object can be converted to POSIXct object, using them as.POSIXct (date) method in R.
The as.POSIXct method converts a date-time string into a POSIXct class. as.POSIXct stores both a date and time with an associated time zone. The default time zone selected, is the time zone that your computer is set to which is most often your local time zone.
The dates are converted to the standard time zone, UTC. A string type date object can be converted to POSIXct object, using them as.POSIXct (date) method in R. “ct” in POSIXct denotes calendar time, it stores the number of seconds since the origin.
R - Date-Time - The POSIX classes. If we have a column containing both date and time we need to use a class that stores both date AND time. Base R offers two closely related classes for date and time: POSIXct and POSIXlt. POSIXct. The as.POSIXct method converts a date-time string into a POSIXct class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With