R strptime of datetime at midnight (00:00:00) gives NA
The base function strptime
gives me output that I am not expecting.
This works as expected:
strptime(20130203235959, "%Y%m%d%H%M%S")
# yields "2013-02-03 23:59:59"
It is too:
strptime(20130202240000, "%Y%m%d%H%M%S")
# yields "2013-02-03"
... but it isn't. Why?
strptime(20130203000000, "%Y%m%d%H%M%S")
# yields NA
UPDATE
The value 20130204000000
appeared in log I generated on Mac 10.7.5 system with command:
➜ ~ echo `date +"%Y%m%d%H%M%S"` 20130204000000
UPDATE 2
I even tried lubridate which seems like a recommendation:
> parse_date_time(c(20130205000001), c("%Y%m%d%H%M%S"))
1 parsed with %Y%m%d%H%M%S
[1] "2013-02-05 00:00:01 UTC"
> parse_date_time(c(20130205000000), c("%Y%m%d%H%M%S"))
1 failed to parse.
[1] NA
... and then, funny enough, he typed "00:00:00" when I added enough seconds now()
to get to midnight:
> now() + new_duration(13000)
[1] "2013-02-10 00:00:00 GMT"
source to share
I have to use character
, not numeric
when parsing my dates:
> strptime(20130203000000, "%Y%m%d%H%M%S") # No! [1] NA > strptime("20130203000000", "%Y%m%d%H%M%S") # Yes! [1] "2013-02-03"
The reason for this is because my value is numeric
getting a value character
and I used too many digits:
> as.character(201302030000) [1] "201302030000" > as.character(2013020300000) [1] "2013020300000" > as.character(20130203000000) [1] "2.0130203e+13" # This causes the error: it doesn't fit "%Y%m%d%H%M%S" > as.character(20130203000001) [1] "20130203000001" # And this is why anything other than 000000 worked.
A quick tutorial on determining the type you want from the docs: In R, execute help(strptime)
and see a popup like the image below.
- The red arrow points to the main argument of the function, but does not indicate the type (which is why I just tried it
numeric
). - The green arrow indicates the type that is in the title of the document.
source to share
you are essentially asking for "zero" second, which obviously does not exist :)
# last second of february 3rd
strptime(20130203235959, "%Y%m%d%H%M%S")
# first second of february 4rd -- notice this 'rounds up' to feb 4th
# even though it says february 3rd
strptime(20130203240000, "%Y%m%d%H%M%S")
# no such second
strptime(20130204000000, "%Y%m%d%H%M%S")
# 2nd second of february 4th
strptime(20130204000001, "%Y%m%d%H%M%S")
source to share