5

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.

plannapus
  • 18,529
  • 4
  • 72
  • 94
stefano
  • 601
  • 1
  • 8
  • 14
  • what do 6.49055593325792 18.2873900837081 mean exactly? what do digits after decimal point represent? – CHP Jan 23 '13 at 15:56
  • and what have you tried? How exactly are you stuck? – Justin Jan 23 '13 at 15:56
  • 2
    I bet it is hours after midnight. I also bet they the author doesn't mean `real` as in a variable type, but as in how a real human reads time. – nograpes Jan 23 '13 at 15:58

3 Answers3

17

@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.

nograpes
  • 18,623
  • 1
  • 44
  • 67
7

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"
Arun
  • 116,683
  • 26
  • 284
  • 387
2

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")
Dinre
  • 4,196
  • 17
  • 26
  • Hi all, I tried all the solutions and all work very well!!!However I am impressed by the fast, easy and simple solution proposed by nograpes! I greatly thank all the helpers!!!Stef – stefano Jan 23 '13 at 22:36
  • @stefano If you like it, click the check beside the answer. – nograpes Jan 25 '13 at 00:19
  • @stefano I think nograpes is referring to the fact that you haven't chosen a "best answer" to your question by clicking the checkmark on StackOverflow, so he isn't getting credit for having his answer chosen. – Dinre Jan 28 '13 at 13:46