0

TPP13.csv is what I get from the original TPP13.xlsx, then I read it:

TPP13<-read.csv("TPP13.csv")

Since the first column contains all the timestamps like "19/11/2020 17:00:00" but in different formats, so I use dmy_hms() and dmy_hm() to transform them respectively.

loops2<-dim(TPP13["TimeStamp1"])[1]

for (i in 1:loops1){
  TPP13["TimeStamp1"][i,]<-dmy_hms(TPP13["TimeStamp1"][i,])
}

for (j in loops1+1:loops2){
  TPP13["TimeStamp1"][j,]<-dmy_hm(TPP13["TimeStamp1"][j,])
}

Then, they are stored in the first column as a seconds format like "1605805200". After that I use as.numeric() and as_datatime() to turn these content to the correct datatime format.

TPP13["TimeStamp1"][1,]<-as.numeric(TPP13["TimeStamp1"][1,])
TPP13["TimeStamp1"][1,]<-as_datetime(as.numeric(TPP13["TimeStamp1"][1,]))
TPP13["TimeStamp1"][1,]
class(TPP13["TimeStamp1"][1,])

However, I find that I failed. TPP13["TimeStamp1"][1,] is still a second format and the class of it is still "character". I do not why I can not change the class of this value.

  • 1
    What do you mean by "correct datetime format", do you mean "YYYY-MM-DD HH:MM:SS"? After using "dmy_hms" or "dmy_hm", the results should be already like "YYYY-MM-DD HH:MM:SS", and the class is ""POSIXct" "POSIXt". – Jeremy May 12 '21 at 15:47
  • You cannot mix classes within a column: if the column is `character`, then when you replace some of the values with numbers, the numbers are converted to strings (because that's what the rest of the column still is). Sample data would make this an easier resolution. See my answer [here]https://stackoverflow.com/a/52319606/3358272), and how it uses "candidate formats" (in a `for` loop) to form a *new* vector of successful conversions. – r2evans May 12 '21 at 16:03
  • Welcome to SO, Qingfei Zhang! I think sample data would be a really good thing to add to this question. Please paste the output from `dput(x)`, where `x` is a representative sample of the different formats you see in your first column. We don't need hundreds, just a dozen or two, feel free to use `head`. In the end, having a reproducible question is very helpful. Thanks! – r2evans May 12 '21 at 16:07

0 Answers0