Steve Shi
Steve Shi

Reputation: 15

how to convert 12 hour to 24 hour in r

I split the time from 2018-12-31 11:45:00 AM to 2018-12-31 and 11:45:00 aAM successfully.

However, I get difficulty that convert "11:45:00 AM" to 24 hours.

I know there are several ways to do that, for example, the most popular way is to use strptime and put format="%I:%M:%S %p. I did that several times and made double checked again and again... but still get N/A in my column. Here is, crimeData is my dataset name, toSplitHrs contains time which is "11:45:00 AM" just like what mentioned:

crimeData$toSplitHrs = strptime(crimeData$SplitHrs, format="%I:%M:%S %p")
Police.Beats    SplitMs SplitHrs year month days hours mins sec toSplitHrs
1           28 2018-12-31 11:45:00 2018    12   31    11   45  00       <NA>
2          177 2018-12-31 11:42:00 2018    12   31    11   42  00       <NA>
3          233 2018-12-31 11:30:00 2018    12   31    11   30  00       <NA>
4           91 2018-12-31 11:30:00 2018    12   31    11   30  00       <NA>
5           73 2018-12-31 11:30:00 2018    12   31    11   30  00       <NA>
6          232 2018-12-31 11:27:00 2018    12   31    11   27  00       <NA>

but still, I got N/A result from that... Also, this dataset contains over 10k observations, I really cannot change them one by one...any suggestions are appreciated!

Upvotes: 0

Views: 188

Answers (1)

Cath
Cath

Reputation: 24074

You can try the format %r for the time, taking into account the am/pm specification (see ?strptime):

strptime("2018-12-31 11:45:00 am", format="%F %r")
#[1] "2018-12-31 11:45:00 CET"
strptime("2018-12-31 11:45:00 pm", format="%F %r")
#[1] "2018-12-31 23:45:00 CET"

Upvotes: 2

Related Questions