14

I have encountered something unexpected while working with the function strptime(). The format of the date I have consists of "1/22/2013 11:00:00 P.M" . The format I am using for this is "%m/%d/%Y %I:%M:%S %p".

The code is as follows.

strptime("1/22/2013 11:00:00 p.m",format="%m/%d/%Y %I:%M:%S %p")
[1] NA

but if I use

strptime("1/22/2013 11:00:00 pm",format="%m/%d/%Y %I:%M:%S %p")
[1] "2013-01-22 23:00:00"

I get the appropriate result.

So does this feature lack in strptime to detect p.m and its variations such as p.m. etc in place of PM or pm. Is this a bug in R ?

The version of R I am using R.14.2 on windows 7 32-bit

Michael
  • 5,808
  • 4
  • 30
  • 39
pmehrotra
  • 143
  • 1
  • 1
  • 4
  • 7
    Please be **very** cautious about labeling behaviors as "bugs" in any established language. It's always tempting to blame software, especially some new package we're not familiar with, but in fact these sort of problems are practically never bugs. (Unless it's SAP, of course :-) ) – Carl Witthoft Jan 22 '13 at 12:42

2 Answers2

12

This is no bug, but strptime expects the information in a standardised way. %p is:

AM/PM indicator in the locale. Used in conjunction with ‘%I’ and not with ‘%H’. An empty string in some locales.

In you locale this is defined as AM/am and PM/pm. R is a formal language, and you need to stick to the rules it imposes. If you define a factor with levels flavor, color, taste, you cannot expect to be able to use colour and flavour as ways to refer to this factor. Even though it seems obvious to you that these represent the same concept, R is a formal language without human flexibility.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
6
library(lubridate)
mdy_hms("01/22/2013 11:00:00 PM")

The result:

[1] "2013-01-22 11:00:00 UTC"
Jaap
  • 81,064
  • 34
  • 182
  • 193
David Wang
  • 111
  • 1
  • 4
  • 3
    In case anyone is wondering, this answer seems to be using the package "lubridate" – andrechalom May 31 '16 at 01:26
  • 4
    11 o'clock (the result) is 11 in the morning, but 11 PM is 11 at night. So your result seem to be wrong. – Rodrigo May 10 '18 at 21:55
  • @Rodrigo has a good point, but I find in my version of `lubridate` correctly interprets this and converts to 23:00 UTC as expected. – El- Jul 07 '20 at 21:25