26

I'm looking to find the day of year for a POSIXct class object with lubridate. For example, 12-9-2015 is day 343.

It's easy to find the day of the week or month with lubridate:

> lubridate::wday("2015-12-09 04:27:56 EST", labels = T)
Wed
> lubridate::day("2015-12-09 04:27:56 EST")
9

Is there an easy way to do so for the day of the year? I've searched the documentation and other questions but have not (yet) found an answer.

Joshua Rosenberg
  • 4,014
  • 9
  • 34
  • 73

2 Answers2

55

The correct function is yday, as in

lubridate::yday(Sys.time())
Jesse Anderson
  • 4,507
  • 26
  • 36
0

Figured out a more complicated way to do this before stumbling on this answer from u/blindjesse:

# compute the time interval from the first of the year until now
YTD = interval(floor_date(now(), unit='year'), now())
# compute the length of the interval in days, and discard the fractional part
as.integer(time_length(YTD, "day"))

By the way, an even more compact version of u/blindjesse's answer would be:

lubridate::yday(now())
Evan Rosica
  • 1,182
  • 1
  • 12
  • 22