Reputation: 145965
The title has it: how do you convert a POSIX date to day-of-year?
Upvotes: 61
Views: 51978
Reputation: 3983
The data.table
package also provides a yday()
function.
require(data.table)
today <- Sys.time()
yday(today)
Upvotes: 2
Reputation: 5137
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')
Upvotes: 4
Reputation: 59525
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
Upvotes: 2
Reputation: 145965
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)
Upvotes: 38
Reputation: 174853
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.
Upvotes: 77