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
481 views
in Technique[技术] by (71.8m points)

r - Convert 12 hour character time to 24 hour

I have a data set with the time in character format. I’m attempting to covert this from a 12 hour format to 24. I have done some searching, but everything I have found seems to assume the characters are already in 24 hour format. Here is an example of the times I'm working with.

times <- c("9:06 AM", "4:42 PM", "3:05 PM", "12:00 PM", "3:38 AM")
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This should work:

times <- c("9:06 AM", "4:42 PM", "3:05 PM", "12:00 PM", "3:38 AM")

strptime(times, "%I:%M %p")

## [1] "2015-04-23 09:06:00 EDT" "2015-04-23 16:42:00 EDT"
## [3] "2015-04-23 15:05:00 EDT" "2015-04-23 12:00:00 EDT"
## [5] "2015-04-23 03:38:00 EDT"

If you want just the times:

format(strptime(times, "%I:%M %p"), format="%H:%M:%S")
## [1] "09:06:00" "16:42:00" "15:05:00" "12:00:00" "03:38:00"

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

...