Geo
Geo

Reputation: 11

Extracting data from pyephem date string in Python

I want to extract the sunrise hour and if I do the following

sun = ephem.Sun()
r1 = home.next_rising(sun)
print ("Visual sunrise %s" % r1)
risehr = r1[10:12]
print ("Rise Hour = %s" % risehr)

I got the error

>>'ephem.Date' object has no attribute '__getitem__'

I can print the string r1 but not extract from it (?) I tried solutions from similar problem posts on extraction but couldn't make any progress, apologies if this appears to be a double post.

Upvotes: 1

Views: 1224

Answers (2)

Matthew Cole
Matthew Cole

Reputation: 597

@kvorobiev answered the question of how to extract from a string representation of your data. But the other half of your question was the error:

'ephem.Date' object has no attribute '__getitem__'

According to the PyEphem documentation for the next_rising() function,

If the search is successful, returns a Date value.

Furthermore, Date objects have an important property:

Dates are stored and returned as floats. Only when printed, passed to str(), or formatted with '%s' does a date express itself as a string giving the calendar day and time.

When you gave the command risehr = r1[10:12], the Python interpreter attempted to get call Date.getattr() to get the fields from a Date object corresponding to the slice 10:12. Without that method, slicing has no meaning to a Date object.

But all is not lost! You can still get the Date object's time information:

Call .tuple() to split a date into its year, month, day, hour, minute, and second.

You can then slice this tuple as needed to get the hour:

hour = r1.tuple()[3]

Or exhaustively:

year, month, day, hour, minute, second = r1.tuple()

Upvotes: 2

kvorobiev
kvorobiev

Reputation: 5070

As I understand your question you want to print only hour of sunrise. r1 is object of ephem.Date type. You could make it with brute force

...
risehr = str(r1)[10:12]
...

or you could convert r1 object to datetime, and datetime to str representation

...
risehr = r1.datetime().strftime('%H') 
...

or convert it to tuple first

...
risehr = r1.tuple()[3]
...

All available options you could read at this page in section Conversions.

Upvotes: 4

Related Questions