user3453272
user3453272

Reputation: 467

convert numeric field to time format in R

I need to convert a numeric field to time format in R

My numeric field is also a little dirty, but the data appears as

9,
1235,
1033,

Each number is the minutes past midnight. i.e. the number "9" is to be interpreted as "9 minutes past midnight".

I tried using strptime(1122, format="%H.%M.")

But I have an error. I get NaN

Please help.

Upvotes: 1

Views: 259

Answers (3)

IRTFM
IRTFM

Reputation: 263301

POSIXct times are generated as GMT and I don't know a reliable way of preventing this:

> tim <- as.POSIXct(Sys.Date())+times*60
> tim
[1] "2014-03-22 17:09:00 PDT" "2014-03-23 13:35:00 PDT" "2014-03-23 10:13:00 PDT"
> tim <- as.POSIXct(Sys.Date(),tz="Americas/Los_Angeles")+times*60
> tim   # Any suggestions to improve this are welcome.
[1] "2014-03-22 17:09:00 PDT" "2014-03-23 13:35:00 PDT" "2014-03-23 10:13:00 PDT"

So I add back 7 hours to get Pacific Daylight time (local for me):

> tim <- as.POSIXct(Sys.Date() )+times*60+3600*7
> tim
[1] "2014-03-23 00:09:00 PDT" "2014-03-23 20:35:00 PDT" "2014-03-23 17:13:00 PDT"

You can get a character output that hides the fact that these are "GMT" locale times:

> tim <- as.POSIXct(Sys.Date() )+times*60
> format(tim, tz="GMT")
[1] "2014-03-23 00:09:00" "2014-03-23 20:35:00" "2014-03-23 17:13:00"

OR without the dates:

> format(tim, "%H:%M:%S", tz="GMT")
[1] "00:09:00" "20:35:00" "17:13:00"

Upvotes: 0

BrodieG
BrodieG

Reputation: 52637

Here is a base version. You need to make sure everything has 4 digits:

vec <- c(9, 1235, 1033)
vec.pad <- sapply(vec, function(x) paste0(c(rep(0, 4 - nchar(x)), x), collapse=""))
strptime(vec.pad, format="%H%M")
# [1] "2014-03-23 00:09:00" "2014-03-23 12:35:00" "2014-03-23 10:33:00"

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269371

Try this:

> library(chron)
> x <- c(9, 1235, 1033)
> times(x / (24 * 60))
[1] 00:09:00 20:35:00 17:13:00

Upvotes: 3

Related Questions