1

Why does as.POSIXct fail to parse 12:00 for me as 00:00:00?

> as.POSIXct('11:59 PM',format='%I:%M %p')
 [1] "2021-10-31 23:59:00 EDT"
> as.POSIXct('12:00 AM',format='%I:%M %p')
 [1] "2021-10-31 EDT"
> as.POSIXct('12:01 AM',format='%I:%M %p')
 [1] "2021-10-31 00:01:00 EDT"
Hasse1987
  • 243
  • 1
  • 9
  • Related: [How can I keep midnight (00:00h) using strptime() in R?](https://stackoverflow.com/questions/37089536/how-can-i-keep-midnight-0000h-using-strptime-in-r) – Henrik Oct 31 '21 at 21:34
  • 1
    `as.POSIXct` doesn't _fail_ to parse midnight, it just doesn't print it. `print.POSIXct` calls `format.POSIXct`, which omits midnight. – Henrik Oct 31 '21 at 22:37
  • @Henrik OK great. I only need the times to do arithmetic on. – Hasse1987 Nov 01 '21 at 00:07

2 Answers2

1

It is related to the format i.e. if we check the ?as.POSIXct

format - character string giving a date-time format as used by strptime.

Therefore, check the ?strptime

format - A character string. The default for the format methods is "%Y-%m-%d %H:%M:%S" if any element has a time component which is not midnight, and "%Y-%m-%d" otherwise. If options("digits.secs") is set, up to the specified number of digits will be printed for seconds.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Additional note: We could use `library(lubridate) hm('12:00 AM')` . – TarJae Oct 31 '21 at 22:11
  • I think the answer could be improved using Henrik's comment, that not only is the behavior related to "format" but it is only related to "format" and not "as.POSIXct", which stores the correct midnight representation. Maybe it's what you meant. – Hasse1987 Nov 01 '21 at 00:09
1

We could use lubridate package:

library(lubridate) 
hm('12:00 AM')
TarJae
  • 72,363
  • 6
  • 19
  • 66