0
votes

Dataset has column Connect.Time with the following structure:

$ Connect.Time      : chr  "7/11/2015 5:53 AM"

With lubridate package I change it to date with the hours & minutes mentioned. This code doesn't work and returns NA

W$Connect.Time <- as.Date(W$Connect.Time, format = "%m/%d/%Y %H:%M")

This gives me "2015-07-11" but R doesn't show the hours and minutes. When trying to extract them hour(W$Connect.Time) it'll give me 0 I'm not sure what to do with the AM/PM either. How to correctly parse it with lubridate package? I want to be able to calculate duration of WiFi sessions in minutes

2
as.Date is not a lubridate function, but a base R. The lubridate function dmy_hm(x) works well.SabDeM
dmy_hm(x) works well indeed. Just ignore the AM/PM notations then?ad_s
@Diederik, as I showed in my answer the lubridate function does not ignore the AM and PM, it just recognize them all and does the proper conversion.SabDeM

2 Answers

3
votes

You can use as.POSIXct(). But in order to get the AM/PM correct you will need to use %I:%M for hours and minutes instead of %H:%M, as %H does not work with %p (the symbol for AM/PM). Note they must be caps, as well.

## July 11, 2015 5:53 am
as.POSIXct("7/11/2015 5:53 AM", format = "%m/%d/%Y %I:%M %p")
# [1] "2015-07-11 05:53:00 PDT"

## July 11, 2015 5:53 pm
as.POSIXct("7/11/2015 5:53 PM", format = "%m/%d/%Y %I:%M %p")
# [1] "2015-07-11 17:53:00 PDT"
1
votes

With lubridate you have to parse it with:

library(lubridate)
x <- "7/11/2015 5:53 AM"
dmy_hm(x)
[1] "2015-11-07 05:53:00 UTC"

The package is smart enough to recognize the AM and PM in your data, so do not worry about that. See the code:

y <- "7/11/2015 5:53 PM"
dmy_hm(y)
[1] "2015-11-07 17:53:00 UTC"

A thing that might be of your concern if the tz argument to set the right time zone.