-1

When converting time in r using as.POSIXct converts all the values to NA. This is my code to do it:

data1 %>%
mutate(time_clean = ymd_hms(timestamp,tz = 'UTC')) %>%
separate(time_clean, c('date', 'time'), sep = ' ') %>%
mutate_at(vars(date), funs(as.Date))

Sample of the data

data1 <- tribble(
~"time", ~"date",
"07:41:47", "2018-11-08",
"07:41:47", "2018-11-08",
"07:41:47", "2018-11-08",
"07:41:50", "2018-11-08",
"07:41:50", "2018-11-08",
"07:41:50", "2018-11-08")
user5576922
  • 103
  • 1
  • 1
  • 7
  • 4
    Please share some lines of data to understand the format. Regarding the format ``%H:%M:%S'` – akrun Jan 10 '19 at 18:33
  • 2
    This is a good link on how to make a good example. Specifically the dput command so we can input your data into R quickly and see what's wonky: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example . Right now I still can't do much with what you have given. – Sahir Moosvi Jan 10 '19 at 19:02
  • 2
    POSIXct is a datetime class, I suspect you are getting NAs because you have times, not datetimes. See [this question](https://stackoverflow.com/questions/22659947/r-how-to-handle-times-without-dates?noredirect=1&lq=1) for suggestions on how to deal with time only data. – Jan Boyer Jan 10 '19 at 19:06
  • I have included the data i am trying to convert. Thanks – user5576922 Jan 10 '19 at 20:38
  • I updated your comment to have a reproducible example. or you could just run your dataframe through dput and copy the result here. You're just passing time and not the date as Jan mentioned above. If you do as.POSIXct(paste(data1 $date, data1 $time)) it will work – Sahir Moosvi Jan 10 '19 at 21:03
  • I have edited my code now can you please point how can i convert the time based on this code please? – user5576922 Jan 10 '19 at 22:30

1 Answers1

0

If you're open to tidyverse solutions, this will accomplish what you need:

library("tidyverse")
# create example data
example_df <- tibble(time = c("07:41:47", "07:41:47", "07:41:50"),
                     date = as.Date(c("2018-11-08", "2018-11-08", "2018-11-08"))) 


example_df %>% 
  unite(col = "datetime",
        c("date", "time"), sep = " ") %>% 
  mutate(datetime = lubridate::ymd_hms(datetime))

But in brief, the issue you're having is related to the fact that as.POSIXct cannot have only a time of the date, without the date. So you need to put date and time in the same string, and then parse it.

If instead you are specifically looking into "time of the day" without date, you may want to check this other question on SO

giocomai
  • 3,043
  • 21
  • 24
  • This seems unnecessarily complicated. Why not just concatenate the two columns as suggested by Sahir Moosvi? – AkselA Jan 10 '19 at 21:38