Convert String of anyformat into dd-mm-yy hh:mm:ss in R

前端 未结 3 546
礼貌的吻别
礼貌的吻别 2020-12-07 04:05

I am reading a date value from csv file.So the format will vary according to the date format of csv. How can I convert any date string to dd-mm-yyy HH:mm:ss ?

ED

相关标签:
3条回答
  • 2020-12-07 04:28

    Try "lubridate" package. Here A_1.csv has both formats.

    Data <-read.csv("Al_1.csv") # import data
    str(Data)
    a = NULL # create a null object
    library(lubridate)
    a$Date <- mdy_hm(Data$Date) # store dd/mm/yyyy HH:mm:ss objects here
    a$Price <- Data$Price # get respective values(it could by any other column)
    b = NULL
    b$Date <- mdy(Data$Date)
    b$Price <- Data$Price
    
    a <- as.data.frame(a)
    b <- as.data.frame(b)
    
    
    a <- a[is.na(a$Date)==FALSE,] # those with NA had diffrent formats remove it
    b <- b[is.na(b$Date)==FALSE,]
    
    b$Date <- as.POSIXlt(b$Date)# change your other format also to UTC
    
    
    x <- rbind(a,b)
    str(x)
    x <- ts(x)
    
    0 讨论(0)
  • 2020-12-07 04:33

    as.Date() converts a string into a Date object. You will need to adapt its format parameter to the specific format your csv has.

    0 讨论(0)
  • 2020-12-07 04:40

    See the anytime package whose anytime function does just that -- and without requiring a format string:

    > inputs <- c("12/07/2017 10:11:12", "12/07/2017", "12-07-2017 10:11:12", 
    +             "07-12-2017", "2017-12-07 10:11:12", "2017-12-07")
    > library(anytime)
    > anytime(inputs)
    [1] "2017-12-07 10:11:12 CST" "2017-12-07 00:00:00 CST"
    [3] "2017-12-07 10:11:12 CST" "2017-07-12 00:00:00 CDT"
    [5] "2017-12-07 10:11:12 CST" "2017-12-07 00:00:00 CST"
    > 
    

    However, your requirement of accepting both d-m-y and m-d-y is not satisfiable. So you need to make a choice and supply an explicit format here.

    In general, I highly recommend avoiding the ambiguity and sticking to y-m-d ISO formats. As a convenience to stubborn North American habits, anytime and anydata also accept m-d-y ordering but it is dangerous.

    Again, only you can tell if 3-4-5 is April 3rd or March 4th, and you need to specify that.

    0 讨论(0)
提交回复
热议问题