问题
I have a timestamp in a dataframe that is recognized as a character class. For some reason, I am not able to convert it to a poxis timestamp.
Here is a sample of the data.
ID dateTime stage
1 2016-11-01T00:00:00.000Z 4.82
2 2016-11-01T00:15:00.000Z 4.83
3 2016-11-01T00:30:00.000Z 4.84
4 2016-11-01T00:45:00.000Z 4.85
5 2016-11-01T01:00:00.000Z 4.86
6 2016-11-01T01:15:00.000Z 4.87
I have tried using the following.
format(df$dateTime, "Y%-%m-%d %h:%m")
as.Date(df$dateTime, "Y%-%m-%d %h:%m")
as.POSIXct(df$dateTime, tz="GMT")
None of the attempts above worked. After trying each, the class would always come out as character.
Any suggestions?
回答1:
We can use anytime
library(anytime)
anytime('2016-11-01T00:15:00.000Z')
#[1] "2016-11-01 00:15:00 IST"
Or use strptime
strptime('2016-11-01T00:15:00.000Z', '%Y-%m-%dT%H:%M:%OSZ')
#[1] "2016-11-01 00:15:00 IST"
回答2:
Z means it's UTC time. So one option is just to strip out the letter and convert to POSIXCT with tz="UTC" . As the dataframe is not easily reproducible, I'm just using the vector of two dates:
x<- as.POSIXct( gsub(pattern = "[A-Z]",replacement = " ",
x = c( "2016-11-01T00:45:00.000Z","2016-11-01T00:39:00.000Z") ) ,
tz="UTC" )
x
class(x)
来源:https://stackoverflow.com/questions/40938733/converting-character-to-timestamp-in-dataframe