Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HH:MM:SS AM/PM string to time

Tags:

time

r

I need to parse times in a character format like "1:36:22 PM".

I've tried various permutations of as.POSIXct and strptime but just can't get there. For example, this fails to pick up the importance of PM:

t <- "1:36:22 PM"
as.POSIXct(t, format = "%H:%M:%S")
# [1] "2016-09-08 01:36:22 BST"

and this fails:

strptime(t, "%H:%M:%S")
# [1] NA

Curiously, for reasons I can't understand, dropping the seconds from the input may work:

t <- "1:30:00 PM"
strptime(t, "%I:%M %p")
# [1] NA
 
t <- "1:30 PM"
strptime(t, "%I:%M %p")
# [1] "2016-09-08 13:30:00 BST"

All I want is for this to work:

t <- "1:30:00 PM"
SOME COMMAND HERE HERE
# [1] "13:30:00"

Any ideas?

like image 672
IanW Avatar asked Sep 08 '16 20:09

IanW


People also ask

How do you convert HH MM to timestamp?

Below is my coding: Object d = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant. DAT_STOPDATE); Date stopDate1 = (Date)d; SimpleDateFormat printFormat = new SimpleDateFormat("hh:mm"); String timeString = printFormat. format(stopDate1);

How do you convert HH MM SS to seconds?

To convert hh:mm:ss to seconds: Convert the hours to seconds, by multiplying by 60 twice. Convert the minutes to seconds by multiplying by 60 .

How do I convert string to minutes?

Split the string into its component parts. Get the number of minutes from the conversion table. Multiply that by the number and that is the number of minutes. Convert that to whatever format you need for the display.


2 Answers

Have you tried using the lubridate package? It can handle AM/PM using the %p indicator in the "parse_date_time" function.

library(lubridate)
t <- "1:36:22 PM"
parse_date_time(t, '%I:%M:%S %p')
[1] "2016-09-08 13:36:22 UTC"

From the lubridate documentation:

%I: Hours as decimal number (01–12 or 1–12).

%M: Minute as decimal number (00–59 or 0–59).

%S: Second as decimal number (00–61 or 0–61).

%P: AM/PM indicator in the locale. Used in conjunction with I and not with H. An empty string in some locales.

like image 183
gillespiecd Avatar answered Oct 03 '22 17:10

gillespiecd


Use the conversion specifications %I and %p. See Details section in ?strptime:

%I Hours as decimal number (01–12).>

%p AM/PM indicator in the locale. Used in conjunction with %I and not with %H.

strptime(t, "%I:%M:%S %p")
like image 21
Shenglin Chen Avatar answered Oct 03 '22 15:10

Shenglin Chen