0

I'm trying to make a function that checks the current time, and tells me if it's before or after sunrise, sunset, dusk, dawn and noon.

But I'm a bit stuck in how to compare the time types I get :(

Can anyone help me out?

This is my code:

now = datetime.now()
now_time = now.time()

print ('\nTime now is %s \n' % now_time)

city_name = 'Stockholm'

a = Astral()

a.solar_depression = 'civil'

city = a[city_name]

print('Information for %s/%s\n' % (city_name, city.region))

timezone = city.timezone

print('Timezone: %s' % timezone)

print('Latitude: %.02f; Longitude: %.02f\n' % \
(city.latitude, city.longitude))

today = datetime.strptime(time.strftime("%Y-%m-%d"), '%Y-%m-%d')

sun = city.sun(date=datetime.date(today), local=True)

dawn = str(sun['dawn'])[11:-6]
sunrise = str(sun['sunrise'])[11:-6]
noon = str(sun['noon'])[11:-6]
sunset = str(sun['sunset'])[11:-6]
dusk = str(sun['dusk'])[11:-6]

print('Dawn:    %s' % dawn)
print('Sunrise: %s' % sunrise)
print('Noon:    %s' % noon)
print('Sunset:  %s' % sunset)
print('Dusk:    %s \n' % dusk)

if now_time > datetime.strptime(dawn, '%H:%M:%S'):
    print ('Time is after dawn')
else:
    print ('Time is before dawn')

It returns this:

Traceback (most recent call last):
  File "test.py", line 63, in <module>
    If now_time > datetime.strptime(dawn, '%H:%M:%S'):
TypeError: can't compare datetime.time to datetime.datetime

1 Answer 1

1

To extract a time object from a datetime object, use the datetime.time() function or the datetime.timetz() function. The latter will retain timezone information, while the former will not.

So change the problem line to this:

if now_time > datetime.strptime(dawn, '%H:%M:%S').time():
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.