I use a function from here to calculate the sunrise and sunset and it returns:
sunrise sunset
6.49055593325792 18.2873900837081
I am struggling (trying with strftime
, POSIXct
or as.Date
functions) to convert it to real time, but so far without success.
As always, any suggestion is greatly appreciated.
@Arun's strategy works, but it might be easier to just do:
x <- c(6.49055593325792, 18.2873900837081)
today<-as.POSIXct('2012-01-23 00:00:00 EST')
today + (3600*x)
# "2012-01-23 06:29:26 EST" "2012-01-23 18:17:14 EST"
That will get you the seconds as well.
First convert the decimal representation to hours and minutes (if I understand it right)
x <- c(6.49055593325792, 18.2873900837081)
# if 6.49 equals 6.49 hours, then do this.
x.m <- paste(floor(x), round((x-floor(x))*60), sep=":")
> x.m
# [1] "6:29" "18:17"
> strptime(x.m, format="%H:%M")
# [1] "2013-01-23 06:29:00" "2013-01-23 18:17:00"
This really depends on what you want to do with this "real time" after it's converted, but I'm going to operate on the assumption that you just want formatted output from the [suncalc] function you're using for readability.
If you just want to display the time in 24-hour / 12-hour format as a string, you could append either of these pairs of lines to the end of your [suncalc] function just before the 'return' statement:
# Use these two lines for 24-hour format
sunrise <- format(as.POSIXct(sunrise*3600, origin="2001-01-01", "GMT"), "%H:%M")
sunset <- format(as.POSIXct(sunset*3600, origin="2001-01-01", "GMT"), "%H:%M")
# Use these two lines for 12-hour format (AM/PM)
sunrise <- format(as.POSIXct(sunrise*3600, origin="2001-01-01", "GMT"), "%I:%M %p")
sunset <- format(as.POSIXct(sunset*3600, origin="2001-01-01", "GMT"), "%I:%M %p")