2

I am trying to calculate the exact amount of daylight hours for a given day and location. I have been looking at the python module "Ephem" for the sunrise and set calculation. Here is the code below:

import ephem
California_forest = ephem.Observer()
California_forest.date = '2001/01/01 00:00'
California_forest.pressure = 0
California_forest.horizon = '-0:34'
California_forest.lat, California_forest.lon = '38.89525', '-120.63275'
California_forest.altitude = 1280

print(California_forest.previous_rising(ephem.Sun()))
2000/12/31 15:21:06

print(California_forest.previous_rising(ephem.Sun()))
2001/1/1 00:50:46

The module works just fine like its tutorial showed. However, I thought you could save the "sunrise" and "sunset" output as a string. When I saved the calculation to a variable, it gives me a floating number that I dont understand:

sunrise = California_forest.previous_rising(ephem.Sun())
sunrise
36890.13965508334

sunset = California_forest.next_setting(ephem.Sun())
sunset
36890.53525430675

I was expecting a string that was the same as the print statement output, but I was mistaken. Does anyone have a suggestion as to how I can use these outputs and calculate the amount of daylight hours for a given location? It would be greatly appreciated!

Jason
  • 181
  • 2
  • 14
  • 1
    What do you get if you `print(repr(sunrise))`, what if you `print(sunrise)` and what if you `print(type(sunrise))`? – zvone Oct 08 '16 at 15:45

2 Answers2

2

It looks like this is returning an ephem._libastro.Date object, which, when convrted to str returns the nicely formatted string you see when printing it.

If you just enter sunrise in the console, that actually does the same as print(repr(sunrise)), which does not produce the nice-looking string. It prints the underlying float value.

If you want to save the string representation, simply convert it to str:

sunrise = str(California_forest.previous_rising(ephem.Sun()))
zvone
  • 18,045
  • 3
  • 49
  • 77
1

What you really what is the string representation of your object. If you must get the string representation of it, then call the __str__() special method as follows.

sunrise = California_forest.previous_rising(ephem.Sun()).__str__()
sunrise
'2000/12/31 15:21:06'

sunset = California_forest.next_setting(ephem.Sun()).__str__()
sunset
'2001/1/1 00:50:46'
emmanuelsa
  • 657
  • 6
  • 9
  • `__str__` is the *special* method called by python interpreter when converting something to `str`. It can be called directly, but it looks much better to simply call `str(whatever)` – zvone Oct 08 '16 at 16:02