R chr data type to Date and Time with AM

Viewed 63

In my table (over 12K lines), I have a Column named Sleep Day that comes in a chr type data with the following info template: 4/12/2016 12:00:00 AM

I tried to convert the chr to Date and time type, but it only shows the Date...

Here is my function (table´s name: conjunta_n):

conjunta_n$SleepDay<-as.Date(conjunta_n$SleepDay, format="%m/%d/%y %H:%M:%S")

The problem is that I keep getting one of these two results:

Output 1: 2020-04-12

Output 2: NA

I haven't been able to get the time part, nor the AM on a date and time template.

The desired output is:

4/12/2016 12:00:00 AM (in date-time type)

Please help!

(I`m new in R)

1 Answers

You can use the lubridate package:

lubridate::mdy_hms("4/12/2016 12:00:00 AM")
lubridate::mdy_hms("4/12/2016 12:00:01 AM")

But there is a gotcha that is unrelated to your conversion method. If the time is exactly midnight, then R will usually print just the date. You can see this here:

> lubridate::mdy_hms("4/12/2016 12:00:00 AM") %>% str
 POSIXct[1:1], format: "2016-04-12"
> lubridate::mdy_hms("4/12/2016 12:00:01 AM") %>% str
 POSIXct[1:1], format: "2016-04-12 00:00:01"

You can also use dput to check that the above two examples differ by one second, but are otherwise the same.

Related