I have a list of dates and times in character strings, and the midnight values have no HH:MM in the string because of the way they were floored to the nearest hour. I am trying to use strftime in R to get all the date-time strings in the same format.
If any of the strings have no HH:MM value, then all of the returned date-time strings are set to 00:00. This behavior began after updating R to 4.3.1.
This line works as expected:
strftime(c("2021-08-09 04:00:00", "2021-08-10 06:00"), format = "%Y-%m-%d %H:%M")
This line coerces everything to midnight:
strftime(c("2021-08-09 04:00:00", "2021-08-10"), format = "%Y-%m-%d %H:%M")
The issue is that
strftimecallsas.POSIXlt(x), which then callsas.POSIXlt.character(x), and then tries to apply theformat=for output after this conversion.The ultimately successful conversion is dictated by the
tryFormats=argument inas.POSIXlt.character(x)The only format that can succeed for both values is
"%Y-%m-%d"so that's what you get, and the hours are dropped. E.g.:This matches what you are seeing:
To get around this, you will need to fill in the times when they are missing using some appropriate logic:
Which will work in
strftimenow too, but this might be redundant: