Convert many formats of date-time to one standard

2020-01-29 03:00发布

I am trying to do some simple operation in R, after loading a table i encountered a date column which has many formats combined.

    **Date**
1/28/14 6:43 PM
1/29/14 4:10 PM
1/30/14 12:09 PM
1/30/14 12:12 PM
02-03-14 19:49
02-03-14 20:03
02-05-14 14:33

I need to convert this to format like 28-01-2014 18:43 i.e. %d-%m-%y %h:%m

I tried this

 tablename$Date <- as.Date(as.character(tablename$Date), "%d-%m-%y %h:%m")

but doing this its filling NA in the entire column. Please help me to get this right!

标签: r datetime
1条回答
做自己的国王
2楼-- · 2020-01-29 03:11

The lubridate package makes quick work of this:

library(lubridate)

d <- parse_date_time(dates, names(guess_formats(dates, c("mdy HM", "mdy IMp"))))
d
## [1] "2014-01-28 18:43:00 UTC" "2014-01-29 16:10:00 UTC"
## [3] "2014-01-30 12:09:00 UTC" "2014-01-30 12:12:00 UTC"
## [5] "2014-02-03 19:49:00 UTC" "2014-02-03 20:03:00 UTC"
## [7] "2014-02-05 14:33:00 UTC"

# put in desired format

format(d, "%m-%d-%Y %H:%M:%S")
## [1] "01-28-2014 18:43:00" "01-29-2014 16:10:00" "01-30-2014 12:09:00"
## [4] "01-30-2014 12:12:00" "02-03-2014 19:49:00" "02-03-2014 20:03:00"
## [7] "02-05-2014 14:33:00"

You'll need to adjust the vector in guess_formats if you come across other format variations.

查看更多
登录 后发表回答