0
import datetime
from suntime import Sun, SunTimeException
from datetime import timedelta

def day_night_time(lat,long,TO_date,TO_time):
    sun = Sun(lat,long)
    date = datetime.date(int(TO_date[:4]), int(TO_date[5:7]), int(TO_date[8:10]))
    TO = datetime.datetime(int(TO_date[:4]), int(TO_date[5:7]), int(TO_date[8:10]),int(TO_time[:2]), int(TO_time[3:5]))

    day_sr = sun.get_local_sunrise_time(date)
    day_ss = sun.get_local_sunset_time(date)
    n_end = day_sr - timedelta(minutes=30)
    n_start = day_ss + timedelta(minutes=30)

    print(TO)
    print(n_end)
    # print(TO-n_end)


day_night_time(50,20,'2020-06-24','10:45:00.000000')

returns

2020-06-24 10:45:00                                                                                                                                                           
2020-06-24 02:02:00+00:00 

I am unable to use this as once has the +00:00 on the end. What is the best way to remove the +00:00 or add it to the other date, so that they can be used. Currrent error: TypeError: can't subtract offset-naive and offset-aware datetimes

Many thanks for your help

tedioustortoise
  • 259
  • 3
  • 20

1 Answers1

2

I'd suggest you also localize TO, so that you have all tz-aware datetime objects. You can easily localize a datetime object to the local timezone by calling the astimezone() method with no timezone specified. I also took the freedom to simplify the code a bit:

from datetime import datetime, timedelta
from suntime import Sun

lat, long, TO_date, TO_time = 49.095, 8.437, '2020-06-24', '10:45:00.000000'

sun = Sun(lat, long)

# making use of input in ISO8601 compatible format,
# and localize to the local timezone:
TO = datetime.fromisoformat(TO_date + 'T' + TO_time).astimezone()

day_sr = sun.get_local_sunrise_time(TO) # 2020-06-24 05:23:00+02:00
day_ss = sun.get_local_sunset_time(TO) # 2020-06-24 21:35:00+02:00

n_end = day_sr - timedelta(minutes=30)
n_start = day_ss + timedelta(minutes=30)

print(TO)
print(n_end)
print(TO-n_end)

# 2020-06-24 10:45:00+02:00
# 2020-06-24 04:53:00+02:00
# 5:52:00

Note that I also adjusted lat/lon so I can verify the result for my location/timezone. As +02:00 indicates, I'm on UTC+2 (CEST).


The other option, if you want to work with all-naive datetime objects, is to replace the tzinfo property with None. In the code above that would look like

TO = datetime.fromisoformat(TO_date + 'T' + TO_time) # 2020-06-24 10:45:00
day_sr = sun.get_local_sunrise_time(TO).replace(tzinfo=None) # 2020-06-24 05:23:00
day_ss = sun.get_local_sunset_time(TO).replace(tzinfo=None) # 2020-06-24 21:35:00

This is also fine since you only work with local times anyway.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72