问题
I have dataset where time.start
vary from 5:00:00 to 28:59:59 (i.e. 01.01.2013 28:00:00 is actually 02.01.2013 04:00:00). Dates are in %d.%m.%Y
format.
Date Time.start
01.01.2013 22:13:07
01.01.2013 22:52:23
01.01.2013 23:34:06
01.01.2013 23:44:25
01.01.2013 27:18:48
01.01.2013 28:41:04
I want to convert it to normal date format.
dates$date <- paste(dates$Date,dates$Time.start, sep = " ")
dates$date <- as.POSIXct(strptime(dates$date, "%m.%d.%Y %H:%M:%S"))
But obviously I have NA
for time > 23:59:59
How should I modify my code?
回答1:
E.g. add the time as seconds to the date:
df <- read.table(header=T, text=" Date Time.start
01.01.2013 22:13:07
01.01.2013 22:52:23
01.01.2013 23:34:06
01.01.2013 23:44:25
01.01.2013 27:18:48
01.01.2013 28:41:04", stringsAsFactors=FALSE)
as.POSIXct(df$Date, format="%d.%m.%Y") +
sapply(strsplit(df$Time.start, ":"), function(t) {
t <- as.integer(t)
t[3] + t[2] * 60 + t[1] * 60 * 60
})
# [1] "2013-01-01 22:13:07 CET" "2013-01-01 22:52:23 CET" "2013-01-01 23:34:06 CET"
# [4] "2013-01-01 23:44:25 CET" "2013-01-02 03:18:48 CET" "2013-01-02 04:41:04 CET"
回答2:
Just a modification of lukeAs solution:
with(df, as.POSIXct(Date, format="%d.%m.%Y")+
colSums(t(read.table(text=Time.start, sep=":",header=F))*c(3600,60,1)))
[1] "2013-01-01 22:13:07 EST" "2013-01-01 22:52:23 EST"
[3] "2013-01-01 23:34:06 EST" "2013-01-01 23:44:25 EST"
[5] "2013-01-02 03:18:48 EST" "2013-01-02 04:41:04 EST"
回答3:
Using lubridate
:
with(dates, mdy(Date) + hms(Time.start))
Generates:
[1] "2013-01-01 22:13:07 UTC" "2013-01-01 22:52:23 UTC"
[3] "2013-01-01 23:34:06 UTC" "2013-01-01 23:44:25 UTC"
[5] "2013-01-02 03:18:48 UTC" "2013-01-02 04:41:04 UTC"
来源:https://stackoverflow.com/questions/24305672/050000-285959-time-format