How to convert a string which is Saturday, 5 Oct 2013 20:31:59
to a datetime format 2013-10-05 Saturday 20:31:59
? Thanks. Or how to get the year
, month
, date
, day of the week
, hour
, minute
, second
values from the string?
You need to use the relevant format specification when you create the time object from the string, eg:
(x <- as.POSIXct("Saturday, 5 Oct 2013 20:31:59", format="%A, %d %b %Y %H:%M:%S"))
[1] "2013-10-05 20:31:59 BST"
Look at ?strftime
to see the format specifications, and how to extract specific parts of a datetime.
#your desired format
format(x, "%Y-%m-%d %A %H:%M:%S")
[1] "2013-10-05 Saturday 20:31:59"
#only the year
format(x,"%Y")
[1] "2013"
> now <- Sys.time()
> now
[1] "2014-01-16 16:58:23 IST"
> as.POSIXlt(as.character(now),tz="GMT")
[1] "2014-01-16 17:05:24 GMT"
> str(as.POSIXlt(now))
POSIXlt[1:1], format: "2014-01-16 16:58:23"
> unclass(as.POSIXlt(now))
$sec
[1] 23.1636
$min
[1] 58
$hour
[1] 16
$mday
[1] 16
$mon
[1] 0
$year
[1] 114
$wday
[1] 4
$yday
[1] 15
$isdst
[1] 0
Using the lubridate
package.
library(lubridate)
x <- "Saturday, 5 Oct 2013 20:31:59"
dmy_hms(x)
## [1] "2013-10-05 20:31:59 UTC"
library(lubridate)
R> date <- now()
R> year(date)
use the below accessor for other
Date component Accessor
Year year()
Month month()
Week week()
Day of year yday()
Day of month mday()
Day of week wday()
Hour hour()
Minute minute()
Second second()
Time zone tz()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.