How do you convert POSIX date to day of year?

RDatetime

R Problem Overview


The title has it: how do you convert a POSIX date to day-of-year?

R Solutions


Solution 1 - R

An alternative is to format the "POSIXt" object using strftime():

R> today <- Sys.time()
R> today
[1] "2012-10-19 19:12:04 BST"
R> doy <- strftime(today, format = "%j")
R> doy
[1] "293"
R> as.numeric(doy)
[1] 293

which is preferable to remembering that the day of the years is zero-based in the POSIX standard.

Solution 2 - R

As ?POSIXlt reveals, a $yday suffix to a POSIXlt date (or even a vector of such) will convert to day of year. Beware that POSIX counts Jan 1 as day 0, so you might want to add 1 to the result.

It took me embarrassingly long to find this, so I thought I'd ask and answer my own question.

Alternatively, the excellent lubridate package provides the yday function, which is just a wrapper for the above method. It conveniently defines similar functions for other units (month, year, hour, ...).

today <- Sys.time()
yday(today)

Solution 3 - R

I realize it isn't quite what the poster was looking for, but I needed to convert POSIX date-times into a fractional day of the year for time series analysis and ended up doing this:

today <- Sys.time()
 
doy2015f<-difftime(today,as.POSIXct(as.Date("2015-01-01 00:00", tzone="GMT")),units='days')

Solution 4 - R

The data.table package also provides a yday() function.

require(data.table)
today <- Sys.time()
yday(today)

Solution 5 - R

This is the way how I do it:

as.POSIXlt(c("15.4", "10.5", "15.5", "10.6"), format = "%d.%m")$yday
# [1] 104 129 134 160

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregor ThomasView Question on Stackoverflow
Solution 1 - RGavin SimpsonView Answer on Stackoverflow
Solution 2 - RGregor ThomasView Answer on Stackoverflow
Solution 3 - RDave XView Answer on Stackoverflow
Solution 4 - RandscharView Answer on Stackoverflow
Solution 5 - RTomasView Answer on Stackoverflow