R: 'strptime' fails to parse output from 'format'

Viewed 39

Let's say I have some date variable which I convert into a string in given format:

mydate <- as.Date("2021-01-01")
myformat <- "%b-%Y"
formatted_date <- format(mydate, myformat)
formatted_date
[1] "Jan-2021"

Now that I've converted it to a string, I then try to read it back to date with the same format, but it does not succeed:

strptime(formatted_date, myformat)
[1] NA

As per the R documentation:

For strptime the input string need not specify the date completely: it is assumed that unspecified seconds, minutes or hours are zero, and an unspecified year, month or day is the current one.

Adding the day at the beginning with %d or similar will make it work, but the docs say it shouldn't be necessary.

Am I missing something?

1 Answers

The complete doc reads :

For strptime the input string need not specify the date completely: it is assumed that unspecified seconds, minutes or hours are zero, and an unspecified year, month or day is the current one. (However, if a month is specified, the day of that month has to be specified by %d or %e since the current day of the month need not be valid for the specified month.) Some components may be returned as NA (but an unknown tzone component is represented by an empty string).

Specifically, the important part here is (However, if a month is specified, the day of that month has to be specified by %d or %e since the current day of the month need not be valid for the specified month.)

Related