How to Convert Numeric Values to Time Without the Date

R: How to handle times without dates?

Use the "times" class found in the chron package:

library(chron)

Enter <- c("09:12", "17:01")
Enter <- times(paste0(Enter, ":00"))

Exit <- c("10:15", "18:11")
Exit <- times(paste0(Exit, ":00"))

Exit - Enter # durations

sum(Enter < "10:00:00") # no entering before 10am
mean(Enter < "10:00:00") # fraction entering before 10am

sum(Exit > "17:00:00") # no exiting after 5pm
mean(Exit > "17:00:00") # fraction exiting after 5pm

table(cut(hours(Enter), breaks = c(0, 10, 17, 24))) # Counts for indicated hours
## (0,10] (10,17] (17,24]
## 1 1 0

table(hours(Enter)) # Counts of entries each hour
## 9 17
## 1 1

stem(hours(Enter), scale = 2)
## The decimal point is at the |

## 9 | 0
## 10 |
## 11 |
## 12 |
## 13 |
## 14 |
## 15 |
## 16 |
## 17 | 0

Graphics:

tab <- c(table(Enter), -table(Exit))  # Freq at each time.  Enter is pos; Exit is neg.
plot(times(names(tab)), tab, type = "h", xlab = "Time", ylab = "Freq")
abline(v = c(10, 17)/24, col = "red", lty = 2) # vertical red lines
abline(h = 0) # X axis

screenshot

Pandas - convert strings to time without date

After performing the conversion you can use the datetime accessor dt to access just the hour or time component:

In [51]:

df['hour'] = pd.to_datetime(df['time'], format='%H:%M').dt.hour
df
Out[51]:
time hour
index
1 10:53 10
2 12:17 12
3 14:46 14
4 16:36 16
5 18:39 18
6 20:31 20
7 22:28 22

Also your format string H%:M% is malformed, it's likely to raise a ValueError: ':' is a bad directive in format 'H%:M%'

Regarding your last comment the dtype is datetime.time not datetime:

In [53]:
df['time'].iloc[0]

Out[53]:
datetime.time(10, 53)

Convert time from numeric to time format in R

You can use as.POSIXct after having multiplied your number by the number of seconds in a day (60 * 60 * 24)

nTime <- c(0.3840277777777778, 0.3847222222222222, 0.3854166666666667)
format(as.POSIXct((nTime) * 86400, origin = "1970-01-01", tz = "UTC"), "%H:%M")
## [1] "09:13" "09:14" "09:15"

How to convert a numeric value into a Date value

We need to specify the origin if it is a numeric value

as.Date(data$Date.birth, origin = "1899-12-30")

e.g.

as.Date(43067, origin = "1899-12-30")
#[1] "2017-11-28"

After converting to Date class, if it needs to be in a custom format, use format

format(as.Date(43067, origin = "1899-12-30"), "%m/%d/%y")
#[1] "11/28/17"

If your column is factor, do convert to numeric first

as.Date(as.numeric(as.character(data$Date.birth)), origin = "1899-12-30")

Converting a numeric value to date time

I have just found the way to do this.

First I have to covert the nvarchar to int then I have to convert it to date time. I have used following code:

Select convert(datetime, (convert (int, [date_column])), 6) as 'convertedDateTime' from mytable


Related Topics



Leave a reply



Submit