Home > Enterprise >  How do I format 12 hour data with am/pm without NAs?
How do I format 12 hour data with am/pm without NAs?

Time:12-15

The reformatting works for just the date, but when I add in the am/pm data it doesn't work. Here is the code and data:

str(Hourly_Steps$activity_hour)
 chr [1:22099] "4/12/2016 12:00:00 AM" "4/12/2016 1:00:00 AM" ...

This worked to format just the date...

    > day <- strptime(Hourly_Steps$activity_hour, format = "%m/%d/%Y %I:%M:%S")
> day
  [1] "2016-04-12 00:00:00 IST" "2016-04-12 01:00:00 IST"
  [3] "2016-04-12 02:00:00 IST" "2016-04-12 03:00:00 IST"
  [5] "2016-04-12 04:00:00 IST" "2016-04-12 05:00:00 IST"
  [7] "2016-04-12 06:00:00 IST" "2016-04-12 07:00:00 IST"
  [9] "2016-04-12 08:00:00 IST" "2016-04-12 09:00:00 IST"
 [11] "2016-04-12 10:00:00 IST" "2016-04-12 11:00:00 IST"

But when I try add in the %p for am/pm info, it goes back to 24hr...

    > day <- strptime(Hourly_Steps$activity_hour, format = "%m/%d/%Y %I:%M:%S %p")
> day
  [1] "2016-04-12 00:00:00 IST" "2016-04-12 01:00:00 IST"
  [3] "2016-04-12 02:00:00 IST" "2016-04-12 03:00:00 IST"
  [5] "2016-04-12 04:00:00 IST" "2016-04-12 05:00:00 IST"
  [7] "2016-04-12 06:00:00 IST" "2016-04-12 07:00:00 IST"
  [9] "2016-04-12 08:00:00 IST" "2016-04-12 09:00:00 IST"
 [11] "2016-04-12 10:00:00 IST" "2016-04-12 11:00:00 IST"
 [13] "2016-04-12 12:00:00 IST" "2016-04-12 13:00:00 IST"
 [15] "2016-04-12 14:00:00 IST" "2016-04-12 15:00:00 IST"

What am I missing here?

CodePudding user response:

Your code works correctly.

You are starting with a "character" vector, and strptime() correctly reads your imperial time into "POSIXt" time format. The "POSIXt" is only stored in this specific "YYYY-MM-DD HH:MM:SS TZ" format and this is what you see displayed.

x <- c("4/12/2016 1:00:00 AM", "4/12/2016 1:00:00 PM", "4/12/2016 12:00:00 AM",
       "4/12/2016 12:00:00 PM")

y <- strptime(x, '%d/%m/%Y %I:%M:%S %p')
y
# [1] "2016-04-12 01:00:00 CEST" "2016-04-12 13:00:00 CEST"
# [3] "2016-04-12 00:00:00 CEST" "2016-04-12 12:00:00 CEST"

and

class(y)
# [1] "POSIXlt" "POSIXt" 

Maybe you are looking for a way to change your output format, where you'd want to use strftime().

z <- strftime(y, '%m/%d/%Y %I:%M:%S %p')
z
# [1] "04/12/2016 01:00:00 am" "04/12/2016 01:00:00 pm"
# [3] "04/12/2016 12:00:00 am" "04/12/2016 12:00:00 pm"

Note, however, that you now have a "character" class.

class(z)
# [1] "character"

So, altogether you may want:

strftime(strptime(x, '%m/%d/%Y %I:%M:%S %p'), '%d/%m/%Y %I:%M:%S %p')
# [1] "12/04/2016 01:00:00 am" "12/04/2016 01:00:00 pm"
# [3] "12/04/2016 12:00:00 am" "12/04/2016 12:00:00 pm"

Sidenote: Midnight may not be displayed even though it is stored internally.

strptime("4/12/2016 12:00:00 AM", '%m/%d/%Y %I:%M:%S %p')
# [1] "2016-04-12 CEST"
  • Related