Convert hour:minute:second (HH:MM:SS) string to proper time class
Use the function chron
in package chron
:
time<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
library(chron)
x <- chron(times=time)
x
[1] 00:00:01 01:02:00 09:30:01 14:15:25
Do some useful things, like calculating the difference between successive elements:
diff(x)
[1] 01:01:59 08:28:01 04:45:24
chron
objects store the values internally as a fraction of seconds per day. Thus 1 second is equivalent to 1/(60*60*24)
, or 1/86400
, i.e. 1.157407e-05
.
So, to add times, one simple option is this:
x + 1/86400
[1] 00:00:02 01:02:01 09:30:02 14:15:26
Convert strings to time format so I can calculate the difference
We can take the difference after converting to ITime
library(dplyr)
library(data.table)
df2 <- df1 %>%
mutate(difference = as.ITime(time_2) - as.ITime(time_1))
or to get the difference in min
utes
df1 %>%
mutate(difference = difftime(as.ITime(time_1),
as.ITime(time_2), units = 'min'))
Converting HH:MM:SS string in .csv to HH:MM:SS vector in R using hms()
Use parse_hms()
rather than as_hms()
How to convert an H:MM:SS time string to seconds in Python?
def get_sec(time_str):
"""Get seconds from time."""
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
print(get_sec('1:23:45'))
print(get_sec('0:04:15'))
print(get_sec('0:00:25'))
Converting character to time in R
We can use times
from chron
to convert to time
library(chron)
times(v1)
#[1] 00:30:00
chron(times(v1))
#[1] (01/01/70 00:30:00)
Or use strptime
to convert to date time objects
r1 <- strptime(v1, format = "%H:%M:%S")
r1
#[1] "2016-05-10 00:30:00 IST"
In addition to strptime
, POSIXct
is also possible
r2 <- as.POSIXct(v1, format = "%H:%M:%S")
r2
#[1] "2016-05-10 00:30:00 IST"
The difference between strptime
and POSIXct
is that the former has POSIXlt
class whereas the latter have only POSIXct
. Also, if we look at the structure of both, the strptime
is stored as a list
is.list(r1)
#[1] TRUE
is.list(r2)
#[1] FALSE
lapply(r1, I)
r1$min
#[1] 30
Another option is lubridate
library(lubridate)
hms(v1)
#[1] "30M 0S"
This also have the date i.e. current date.
The as.Date
only converts to 'Date'. It doesn't show any time.
data
v1 <- "0:30:00"
Individually available Hour Minute Seconds to HH:mm:ss format
Something like this:
String.format("%02d:%02d:%02d", e.getHours(), e.getMinutes(), e.getSeconds())
JavaScript seconds to time string with format hh:mm:ss
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
You can use it now like:
alert("5678".toHHMMSS());
Working snippet:
String.prototype.toHHMMSS = function () { var sec_num = parseInt(this, 10); // don't forget the second param var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} return hours + ':' + minutes + ':' + seconds;} console.log("5678".toHHMMSS());
Formatting a Duration like HH:mm:ss
You can use Duration
and implement this method:
String _printDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
Usage:
final now = Duration(seconds: 30);
print("${_printDuration(now)}");
Related Topics
How to Assign a Unique Id Number to Each Group of Identical Values in a Column
Construct a Manual Legend For a Complicated Plot
How to Replace Na Values in a Table For Selected Columns
Dummy Variables from a String Variable
How to Read a CSV File in R With Different Number of Columns
How to Print When Using %Dopar%
Create Integer Sequences Defined by 'From' and 'To' Vectors
Sample N Random Rows Per Group in a Dataframe
Explain a Lazy Evaluation Quirk
Change the Blank Cells to "Na"
Plot Multiple Lines (Data Series) Each With Unique Color in R