Reputation: 3980
I have imported some data into R, which looks like the following:
dateTime temp
1 10/25/2005 12:00:00 15.50
2 10/25/2005 1:00:00 15.49
3 10/25/2005 2:00:00 15.52
4 10/25/2005 3:00:00 15.50
5 10/25/2005 4:00:00 15.50
6 10/25/2005 5:00:00 15.46
where the class of the dateTime column of the data.frame is factor and the second column is numeric.
I try to convert the dateTime into POSIXct format as follows:
dat[,1] <- as.POSIXct(dat[,1])
but receive the error
Error in as.POSIXlt.character(as.character(x), ...) :
character string is not in a standard unambiguous format
which I think is to do with the dateTime varying in the format that hour is presented e.g. 12, 1, 2 etc and not 12, 01, 02.
How can I change this to POSIXct?
Upvotes: 1
Views: 3871
Reputation: 132706
You need to specify the format:
datetime <- factor("10/25/2005 12:00:00")
as.POSIXct(datetime)
#Error in as.POSIXlt.character(as.character(x), ...) :
# character string is not in a standard unambiguous format
as.POSIXct(datetime, format="%m/%d/%Y %H:%M:%S")
#[1] "2005-10-25 12:00:00 CEST"
Note: I advise you to always specify a time zone explicitly when creating datetime variables. Otherwise, you could get into trouble with daylight saving time.
as.POSIXct(datetime, format="%m/%d/%Y %H:%M:%S", tz="GMT")
#[1] "2005-10-25 12:00:00 GMT"
Upvotes: 3