R - convert POSIXct to fraction of julian day

1.6k Views Asked by At

How can a date/time object in R be transformed on the fraction of a julian day?

For example, how can I turn this date:

date <- as.POSIXct('2006-12-12 12:00:00',tz='GMT')

into a number like this

> fjday
[1] 365.5

where julian day is elapsed day counted from the january 1st. The fraction 0.5 means that it's 12pm, and therefore half of the day.

This is just an example, but my real data covers all the 365 days of year 2006.

3

There are 3 best solutions below

4
On

Since all your dates are from the same year (2006) this should be pretty easy:

julian(date, origin = as.POSIXct('2006-01-01', tz = 'GMT'))

If you or another reader happen to expand your dataset to other years, then you can set the origin for the beginning of each year as follows:

sapply(date, function(x) julian(x, origin = as.POSIXct(paste0(format(x, "%Y"),'-01-01'), tz = 'GMT')))
0
On

Have a look at the difftime function:

> unclass(difftime('2006-12-12 12:00:00', '2006-01-01 00:00:00', tz="GMT", units = "days"))
[1] 345.5
attr(,"units")
[1] "days"
0
On

A function to convert POSIX to julian day, an extension of the answer above, source it before using.

julian_conv <- function(x) { 
if (is.na(x)) { # Because julian() cannot accept NA values
  return(NA)
}
else {
j <-julian(x, origin = as.POSIXlt(paste0(format(x, "%Y"),'-01-01')))
temp <- unclass(j) # To unclass the object julian day to extract julian day
return(temp[1] + 1) # Because Julian day 1 is 1 e.g., 2016-01-01
}
}

Example:

date <- as.POSIXct('2006-12-12 12:00:00')
julian_conv(date)
#[1] 345.5