Convert an Integer Column to Time Hh:Mm

Convert an integer column to time HH:MM

Here's one suggestion

temp <- c(0 ,  5 , 10,  15  ,20 , 25  ,30  ,35,  40,  45 , 50  ,55 ,100 ,105, 110) # Your data
temp2 <- mapply(function(x, y) paste0(rep(x, y), collapse = ""), 0, 4 - nchar(temp))
temp <- paste0(temp2, temp)
temp
# [1] "0000" "0005" "0010" "0015" "0020" "0025" "0030" "0035" "0040" "0045" "0050" "0055" "0100" "0105" "0110"

Then you can do

format(strptime(temp, format="%H%M"), format = "%H:%M")
#[1] "00:00" "00:05" "00:10" "00:15" "00:20" "00:25" "00:30" "00:35" "00:40" "00:45" "00:50" "00:55" "01:00" "01:05" "01:10"

Convert column of integers to time in HH:MM:SS format efficiently

This is possible with some simple timdelta arithmetic:

df['24Hr Time'] = (
pd.to_timedelta((df['Time'] - 1) * 15, unit='m') + pd.Timedelta(hours=8))
df.head()

Time 24Hr Time
0 1 08:00:00
1 1 08:00:00
2 1 08:00:00
3 2 08:15:00
4 2 08:15:00

df.dtypes

Time int64
24Hr Time timedelta64[ns]
dtype: object

If you need a string, use pd.to_datetime with unit and origin:

df['24Hr Time'] = (
pd.to_datetime((df['Time']-1) * 15, unit='m', origin='8:00:00')
.dt.strftime('%H:%M:%S'))
df.head()

Time 24Hr Time
0 1 08:00:00
1 1 08:00:00
2 1 08:00:00
3 2 08:15:00
4 2 08:15:00

df.dtypes

Time int64
24Hr Time object
dtype: object

converting time that is an int in HHMM format and creating an hour field from it using pandas

One way using pandas.Series.str.zfill:

s = pd.Series([1, 450, 2320, 545, 350, 2100])
pd.to_datetime(s.astype(str).str.zfill(4), format="%H%M")

Output:

0   1900-01-01 00:01:00
1 1900-01-01 04:50:00
2 1900-01-01 23:20:00
3 1900-01-01 05:45:00
4 1900-01-01 03:50:00
5 1900-01-01 21:00:00

Explain:

  • str.zfill(n) pads zeros on the left of its inputs; so your ints become a string with at most 4 digits.

    0    0001
    1 0450
    2 2320
    3 0545
    4 0350
    5 2100
  • pd.to_datetime then uses the string to parse based on format, i.e. HHMM (%H%M).

How to convert an integer value to time (HH:MM:SS) in SQL Server?

You can use TIMEFROMPARTS

SELECT
TIMEFROMPARTS(
YourColumn / 10000,
YourColumn / 100 % 100,
YourColumn % 100
)
FROM YourTable;

How to convert int column in time HH:MM in SQL?

Convert your time fields into minutes, and then do the math on the minutes. This example uses two variables - you'd use your field names instead.

Declare
@Allotted As Time = '08:00'
, @Taken As Time = '06:00'

Select Cast(DateDiff(Minute, '00:00', @Taken) As Numeric(17, 2)) / DateDiff(Minute, '00:00', @Allotted) as Percent_Of_Allotted_Time

How can I convert number to hh:mm:ss?

Convert the seconds to period (seconds_to_period) and use hms from hms package

library(lubridate)
library(dplyr)
df1 <- df1 %>%
transmute(Time = hms::hms(seconds_to_period(hrsecs)))

-output

df1
Time
1 00:26:03
2 03:38:08
3 03:58:29

data

df1 <- structure(list(hrsecs = c(1563L, 13088L, 14309L)), 
class = "data.frame", row.names = c(NA,
-3L))


Related Topics



Leave a reply



Submit