1

As described here and in other questions, it's fairly straight-forward to convert a Date object to POSIXct -- with the gotcha from ?as.POSIXct that dates without times are treated as being midnight UTC. For example:

> Sys.timezone()
[1] "Europe/London"
> d <- as.Date("2016-06-01")
> as.POSIXct(d)
[1] "2016-06-01 01:00:00 BST"

I have two questions:

1) Why UTC? Wouldn't midnight in your current timezone make more sense, i.e. 2016-06-01 00:00:00 BST?

2) Is there a more elegant way to get the actual midnight for a date than the following:

as.POSIXct(as.character(d))

By way of explanation, I have a function that takes a Date as an argument and then finds all the log events that happened on or after that date. With the standard behaviour outlined above, I'm missing all of the events between midnight and 1 am, and so I'm having to add the as.character cast.

Community
  • 1
  • 1
jkeirstead
  • 2,881
  • 3
  • 23
  • 26
  • Try specifying your timezone during conversion: `as.POSIXct("2016-06-01", tz="Europe/London")`. See `OlsonNames()` for the complete list of acceptable timezones names. – Dave2e Aug 16 '16 at 13:28
  • 1
    This works because the first argument is a character, not a Date object. – jkeirstead Aug 16 '16 at 13:33
  • I think `lubridate::parse_date_time()` might be useful here – Nate Aug 16 '16 at 13:33
  • @NathanDay `parse_date_time(d, "ymd", tz = "Europe/London")` does the trick. That's about the same amount of typing as `as.character` but thanks for highlighting that function. – jkeirstead Aug 16 '16 at 13:41
  • `ymd("2016-06-01", tz = Sys.timezone())` a convience wrapper if you don't need to power or matching multiple or custom orders. – Nate Aug 16 '16 at 13:55

0 Answers0