2

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.

thiagoveloso
  • 2,537
  • 3
  • 28
  • 57

3 Answers3

4

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')))
CephBirk
  • 6,422
  • 5
  • 56
  • 74
  • Thanks a lot for your answer, @CephBirk. However, it is not in the time difference that I am interested, but instead in the "true" date conversion. For example, 2006-01-01 12:00:00 would be 1.5. – thiagoveloso Dec 21 '14 at 22:12
  • 2
    What do you mean? Why are you expecting noon at January 1st to be 1.5 days since the new year? – CephBirk Dec 21 '14 at 22:16
  • Yes, julian days work like this: january 1st is jday 01, january 2nd is jday 02, ..., february 1st is jday 32 and so on. Just take a look at this: http://landweb.nascom.nasa.gov/browse/calendar.html. Then the fraction of the julian day would refer to the hour. Then, for example, february 1st at 01am would be 32 + (01/24), then 2am would 32 + (02/24) and so on. I'm sure there's no need to define this function by hand, there must be a package that makes things easier... – thiagoveloso Dec 21 '14 at 22:23
  • Now, I am certainly not an expert on Julian days, but I'm pretty sure the system starts at zero. If you've been working with this date format for awhile then feel free to ignore this, and you can just add +1 to the end of the line. – CephBirk Dec 21 '14 at 22:35
2

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"
Jeroen Ooms
  • 31,998
  • 35
  • 134
  • 207
2

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
Yusri
  • 282
  • 1
  • 4
  • 16