Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

r - Converting to date in a character column that contains two date formats

I have CSV file with "date" column but it contains two different date format as the following

7/12/2015 15:28 as m/d/yyyy hh:mm
18-04-2016 18:20  as d/m/yyyy hh:mm

How can I change the format into m/d/yyyy hh: mm, So I can subtract the dates from each other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

External packages are not required if you simply have two datetime formats. Just run both formats through the parser and take the non-missing one:

x <- c("7/12/2015 15:28","18-04-2016 18:20")
pmax(
  as.POSIXct(x, format="%m/%d/%Y %H:%M", tz="UTC"),
  as.POSIXct(x, format="%d-%m-%Y %H:%M", tz="UTC"),
  na.rm=TRUE
)
#[1] "2015-07-12 15:28:00 UTC" "2016-04-18 18:20:00 UTC"

As far as I know, there is absolutely no way to deal with ambiguous date formats automatically, so hard-coding is the way to go here probably.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...