28

Consider the following timestamp

timestamp <- ymd_hms("2011-08-10 14:00:00", tz = "Pacific/Auckland")

> timestamp
[1] "2011-08-10 14:00:00 NZST"

What is the simplest way to get the day part 2011-08-10 from it, and making sure this day is a proper date and not a string?

Using lubridate::day(timestamp) obviously fails here.

zx8754
  • 52,746
  • 12
  • 114
  • 209
ℕʘʘḆḽḘ
  • 18,566
  • 34
  • 128
  • 235
  • 8
    Just do `as.Date` – akrun Oct 24 '16 at 15:30
  • 4
    I think you're looking for `lubridate::date`. The difference from `as.Date` is that `date` uses the date as it exists in the assigned time zone instead of converting to UTC first (the default in `as.Date`, though it can take a `tz` parameter). – alistaire Oct 24 '16 at 15:33
  • 3
    `floor_date(timestamp,"day")` yields a POSIXct with the right timezone... – Erwan LE PENNEC Oct 24 '16 at 19:35
  • I think you can also use lubridate and as_date now versus as_datetime `mutate(day=as_datetime(timestamp))` and this will work within a pipe – Bill Perry Dec 12 '17 at 17:14

3 Answers3

29

This would probably be the simplest way:

date(timestamp)

It will return a date class and not a string.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
doron
  • 454
  • 6
  • 10
14

Use date instead of day

lubridate::date(timestamp)
Praveen Kumar
  • 321
  • 3
  • 5
4

There is also data.tables as.IDate() function now:

timestamp <- "2011-08-10 14:00:00"
data.table::as.IDate(timestamp)
andschar
  • 3,504
  • 2
  • 27
  • 35