2

I'm trying to convert some timestamps (character) to a POSIXct object:

> u <- "December 05, 2017 1:00 PM"

I'm using as.POSIXct as below:

> as.POSIXct(u, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 01:00:00 UTC"

I would expect the output to show 13 for the hour instead of 01:

"2017-12-05 13:00:00 UTC"

I've seen the question posted here: Parse timestamp with a.m./p.m but I seem to have the correct input and format string (with %p).

as.POSIXct appears to completely ignore the AM/PM part of the string and therefore the AM timestamps work fine but the PM stamps lag by 12 hours. Here's some more data to illustrate this:

> sample_tstamps
 [1] "December 05, 2017 8:00 AM"  "December 05, 2017 9:00 AM"  "December 05, 2017 10:00 AM" "December 05, 2017 11:00 AM"
 [5] "December 05, 2017 12:00 PM" "December 05, 2017 1:00 PM"  "December 05, 2017 2:00 PM"  "December 05, 2017 3:00 PM" 
 [9] "December 05, 2017 4:00 PM"  "December 05, 2017 5:00 PM" 
> as.POSIXct(sample_tstamps, format = "%B %d, %Y %H:%M %p", tz = "UTC")
 [1] "2017-12-05 08:00:00 UTC" "2017-12-05 09:00:00 UTC" "2017-12-05 10:00:00 UTC" "2017-12-05 11:00:00 UTC"
 [5] "2017-12-05 12:00:00 UTC" "2017-12-05 01:00:00 UTC" "2017-12-05 02:00:00 UTC" "2017-12-05 03:00:00 UTC"
 [9] "2017-12-05 04:00:00 UTC" "2017-12-05 05:00:00 UTC"
Gautam
  • 2,597
  • 1
  • 28
  • 51

2 Answers2

2

We need %I instead of %H

as.POSIXct(u, format = "%B %d, %Y %I:%M %p", tz = "UTC")
#[1] "2017-12-05 13:00:00 UTC"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks, it seems to work and I'll update the code. I'm surprised though - I've always used `%H` in the past (see https://www.stat.berkeley.edu/~s133/dates.html) without any problems. – Gautam Dec 05 '17 at 14:16
1

Using the R-package lubridate:

u <- "December 05, 2017 1:00 PM"
lubridate::mdy_hm(u)
#[1] "2017-12-05 13:00:00 UTC"
J_F
  • 9,956
  • 2
  • 31
  • 55
  • Thanks, I'm able to use this but I don't want to use any external packages for this specific problem. – Gautam Dec 05 '17 at 14:17