Date to day and time

Viewed 56

I have read a lot of blogs, but I cannot find the answer to my question:

I have a date 2020-25-02 17:45:03 and I would like to convert it to two columns day and time.

hello <- strptime(as.character("2020-25-02 17:42:03"),"%Y-%m-%d %H:%M:%S")
df$day <- as.Date(hello, format = "%Y-%d-%m")

But I also would like df$time. Is it possible ?

2 Answers
 dtimes = c("2002-06-09 12:45:40","2003-01-29 09:30:40",
+            "2002-09-04 16:45:40","2002-11-13 20:00:40",
+            "2002-07-07 17:30:40")
> dtparts = t(as.data.frame(strsplit(dtimes,' ')))
> row.names(dtparts) = NULL
> thetimes = chron(dates=dtparts[,1],times=dtparts[,2],
+                  format=c('y-m-d','h:m:s'))
> thetimes
[1] (02-06-09 12:45:40) (03-01-29 09:30:40) (02-09-04 16:45:40)
[4] (02-11-13 20:00:40) (02-07-07 17:30:40)

Please see this link

Use function hms in package lubridate.

df <- data.frame(day = as.Date(hello, format = "%Y-%d-%m"))
df$time <- lubridate::hms(sub("^[^ ]*\\b(.*)$", "\\1", hello))

df
#         day       time
#1 2020-02-25 17H 42M 3S

str(df)
#'data.frame':  1 obs. of  2 variables:
# $ day : Date, format: "2020-02-25"
# $ time:Formal class 'Period' [package "lubridate"] with 6 slots
#  .. ..@ .Data : num 3
#  .. ..@ year  : num 0
#  .. ..@ month : num 0
#  .. ..@ day   : num 0
#  .. ..@ hour  : num 17
#  .. ..@ minute: num 42
Related