示例#1
0
def index(lat, lng):
    obs = get_obs()
    closest = sorted(obs,
                     key=lambda o: calc_distance(float(o[0][
                         'lat']), float(o[0]['lon']), lat, lng))[0]
    stk = [x for x in obs if x[0]["stn_name"] == "ST KILDA HARBOUR - RMYS"]
    if len(stk):
        stk = {
            "wind_spd_kt": stk[0][1]["wind_spd"],
            "wind_dir": stk[0][1]["wind_dir"]
        }
    else:
        stk = {"wind_spd_kt": "", "wind_dir": ""}
    forecast = get_forecast()
    sun = Sun(lat, lng)
    sunr = sun.get_sunrise_time().timestamp()
    sund = sun.get_sunset_time().timestamp()
    return json.dumps({
        "closest": {
            "stn":
            closest[0]["description"],
            "wind_dir":
            closest[1]["wind_dir"],
            "wind_spd_kt":
            closest[1]["wind_spd"],
            "app_tmp":
            closest[1]["apparent_temp"],
            "rel_humidity":
            closest[1]["rel_humidity"],
            "ts":
            round(
                datetime.datetime.strptime(closest[1]["datetime"],
                                           "%Y-%m-%dT%H:%M:%S%z").timestamp()),
        },
        "srss": [round(sunr), round(sund)],
        "stk": stk,
        "forecast": forecast,
    })
示例#2
0
def get_timezone(latitude, longitude):
    #Get today sunrise and sunset
    sun = Sun(latitude, longitude)
    today_sr = int(sun.get_sunrise_time().strftime('%H'))
    today_ss = int(sun.get_sunset_time().strftime('%H'))

    #Get timezone
    tf = TimezoneFinder()
    timezone = tf.timezone_at(lng=longitude, lat=latitude) # returns 'Europe/Berlin'

    #Get time
    tz = pytz.timezone(timezone)
    timezone_now = int(datetime.datetime.now(tz).strftime('%H'))

    logging.info(str(timezone_now))
    logging.info(str(today_sr))
    logging.info(str(today_ss))

    if timezone_now > today_sr and timezone_now < today_ss:
        day = "Day"
    else:
        day = "Night"

    return day
    ind_array = np.concatenate(([0], ind_array), axis=0)
    ind_array = np.concatenate((ind_array, [len(np_cast) - 1]), axis=0)

    # calculating the sunrise and sunset times for each cast (if possible)
    # If the lattitudes are in the far north or south during summer/winter
    # There are no sunrise or sunset as it will all be day or night
    # All the times are in UTC
    k = 0
    for j in range(len(ind_array) - 1):

        d = date(np_year[ind_array[j]], np_month[ind_array[j]],
                 np_day[ind_array[j]])
        sun = Sun(np_lat[ind_array[j]], np_long[ind_array[j]])

        try:
            sr = sun.get_sunrise_time(d)
            ss = sun.get_sunset_time(d)

        except:
            # Any operation here is needed for the try method
            k += 1

        else:
            # IF the sunrise can be calculated, then we use the suntime module
            # to compute the sunrise and sunset times for each cast
            sr = sun.get_sunrise_time(d)
            ss = sun.get_sunset_time(d)
            np_sr[ind_array[j]:ind_array[j + 1]] = round(
                sr.hour + sr.minute / 60, 2)
            np_ss[ind_array[j]:ind_array[j + 1]] = round(
                ss.hour + ss.minute / 60, 2)
示例#4
0
# PIN connected to water pump
bomba = 23

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(bomba, GPIO.OUT)

# coordenadas Covilhã
latitude = 40.28
longitude = -7.50
utc = pytz.utc

sun = Sun(latitude, longitude)

nascerSol = sun.get_sunrise_time()
porSol = sun.get_sunset_time()

#horario de verao
now = datetime.now().replace(tzinfo=utc)
dia = now.day
mes = now.month
hoje = (mes, dia)
iniVerao = (3, 29)
fimVerao = (10, 25)

if iniVerao < hoje < fimVerao:
    nascerSol = nascerSol + timedelta(hours=1)
    porSol = porSol + timedelta(hours=1)

print("Agora: ", str(now))
示例#5
0
import datetime
from suntime import Sun, SunTimeException

# Lyon
latitude = 45.75
longitude = 4.85

sun = Sun(latitude, longitude)

# Get today's sunrise and sunset in UTC
today_sr = sun.get_sunrise_time()
today_ss = sun.get_sunset_time()
print('Today at Lyon the sun raised at {} and get down at {} UTC'.format(
    today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M')))

# On a special date in your machine's local time zone
abd = datetime.date(2020, 9, 25)
abd_sr = sun.get_local_sunrise_time(abd)
abd_ss = sun.get_local_sunset_time(abd)
print(
    'On {} the sun at Lyon raised at {} and get down at {}. local time'.format(
        abd, abd_sr.strftime('%H:%M'), abd_ss.strftime('%H:%M')))
示例#6
0
class SolarPower:
    def __init__(self):
        #Solar Array Data
        self.itemCode = "ALTS-200W-24P"
        self.solarPanelEfficiency = 0.1572  #Prosent
        self.solarPanelMinTemp = -40  # Celsius
        self.solarPanelMaxTemp = 80  # Celsius
        self.solarPanelPower = 4864  # W
        self.solarPanelArea = 32  # m^2
        self.powersqm = 153  #W/m^2

        # Constants
        self.solarIridiationConstant = 1367  #W/m^2
        self.solarPanelMaxCloudLoss = 0.30  # prosent
        self.lat = 63.42
        self.lon = 10.40
        self.city = "Trondheim"
        self.sun = Sun(self.lat, self.lon)

        #data
        self.weatherData = self.getWeatherDataFromFile()

        #Weather Data
        self.key = "8554bc4036b0ec568b136bbba124d344"
        self.url = f"https://api.openweathermap.org/data/2.5/weather?lat={self.lat}&lon={self.lon}&appid={self.key}"

    def getWeatherDataFromFile(self):
        #data = pd.read_csv("weatherHistoryHourly.csv", dtype={"dt": "int64", "clouds_all":"int64"}, parse_dates=["dt_iso"])
        data = pd.read_csv("newWeatherData.csv",
                           dtype={
                               "dt": "int64",
                               "clouds_all": "int64"
                           },
                           parse_dates=["dt_iso"])
        return data

    def getIridiationDataFromFile(self):
        irridiationData = pd.read_csv("solarIridiation.csv",
                                      dtype={"P": "float64"})
        return irridiationData

    def weatherCoefficient(self,
                           timestamp=None,
                           date=None,
                           row=None,
                           data=None):

        if timestamp != None:
            cloud_coverage = row = data.loc[data["dt"] == timestamp,
                                            "clouds_all"]
            cloudCoefficient = 1 - (self.solarPanelMaxCloudLoss *
                                    cloud_coverage / 100)

            return cloudCoefficient

        elif date != None:
            pass

        elif row != None:
            cloud_coverage = data["clouds_all"][row]
            cloudCoefficient = 1 - (self.solarPanelMaxCloudLoss *
                                    cloud_coverage / 100)

            return cloudCoefficient

        else:
            return 1

        return 1

    def irradiationCoefficient(self, timestamp=None, data=None):
        return 1

    def powerCalculationHour(self, timestamp=None, row=None, data=None):

        timestamp = data["dt"][row]
        sunRise = self.sun.get_sunrise_time(
            datetime.datetime.utcfromtimestamp(timestamp)).replace(tzinfo=None)
        sunSet = self.sun.get_sunset_time(
            datetime.datetime.utcfromtimestamp(timestamp)).replace(tzinfo=None)
        dataTime = datetime.datetime.utcfromtimestamp(timestamp)

        if sunRise < dataTime < sunSet:
            return self.solarIridiationConstant * self.solarPanelEfficiency * self.weatherCoefficient(
                row=row, data=data) * self.irradiationCoefficient()

        else:
            return 0

    def updateHistoricSolarPowerGeneration(self):
        data = self.getWeatherDataFromFile()
        data.loc[:, "generated_solar_power[Wh]"] = 0.1
        iri = self.getIridiationDataFromFile()

        for i in range(len(data["dt"]) - 1):
            timeC = datetime.datetime.utcfromtimestamp(
                data["dt"][i]).strftime("%m%d%H%M")
            series = iri.loc[iri["dateC"] == int(timeC), "P"]

            try:
                power = series.to_list()[0]
            except:
                timeC = datetime.datetime.utcfromtimestamp(
                    data["dt"][i - 1]).strftime("%m%d%H%M")
                series = iri.loc[iri["dateC"] == int(timeC), "P"]
                power = series.to_list()[0]

            data.loc[i,
                     "generated_solar_power[Wh]"] = power * self.solarPanelArea

        data.loc[:, "generated_solar_power[Wh]"].astype(float)
        """
       for i in range(len(data["dt"])):
           #data2["generated_solar_power[Wh]"][i] = self.powerCalculationHour(data["dt"][i])
           data.loc[:,"generated_solar_power[Wh]"].iloc[i] = self.powerCalculationHour(row = i, data=data)
           #print(f"{data['generated_solar_power[Wh]'][i]}  =   {self.powerCalculationHour(row = i)}")  
           
       """
        data.to_csv("newWeatherData.csv", index=False)

        return data

    def updateHistoricWeatherData(self):

        oldWeatherData = self.getWeatherDataFromFile()  # Get data
        lastOldDataTimestamp = oldWeatherData.loc[:, "dt"].iloc[
            len(oldWeatherData["dt"]) - 1] + 86400  # Last Timestamp
        lastOldDataDate = datetime.datetime.utcfromtimestamp(
            lastOldDataTimestamp)  # Last Timestamp in datetime format
        lastOldDataDay = lastOldDataDate.replace(hour=0)  # Last timestamp day

        currentDate = datetime.datetime.utcnow()
        currentDateTimestamp = int(currentDate.timestamp())

        deltatime = (currentDate - lastOldDataDay)

        df = df2 = pd.DataFrame(columns=oldWeatherData.columns)

        for days in range(deltatime.days):

            if (deltatime.days - days) < 5:
                timestamp = int(
                    (lastOldDataDay +
                     datetime.timedelta(days=days)).timestamp()) + 7200
                data = self.getHistoricWeatherDataFromTimestamp(timestamp)
                df2 = pd.DataFrame(
                    data["hourly"]).rename(columns={"clouds": "clouds_all"})

                df = df.append(df2).reset_index(drop=True)

            else:
                yesterdayTimestamp = int(
                    (lastOldDataDay + datetime.timedelta(days=deltatime.days) -
                     datetime.timedelta(days=1)).timestamp())
                data = self.getHistoricWeatherDataFromTimestamp(
                    yesterdayTimestamp)
                df2 = pd.DataFrame(
                    data["hourly"]).rename(columns={"clouds": "clouds_all"})

                timestamp = int((lastOldDataDay +
                                 datetime.timedelta(days=days)).timestamp() +
                                7200)
                #return lastOldDataDay
                for n in range(len(df2["dt"])):
                    df2["dt"][n] = timestamp + 3600 * n

                df = df.append(df2).reset_index(drop=True)

        df.loc[:, "dt"] = pd.to_numeric(df["dt"]).astype(int)

        for i in range(len(df["dt"])):

            df.loc[:, "dt_iso"].iloc[i] = str(
                datetime.datetime.utcfromtimestamp(df["dt"][i])) + " +0000 UTC"

        newWeatherData = oldWeatherData.append(df)
        newWeatherData.to_csv("newWeatherData.csv", index=False)

        return (df)

    def getHistoricWeatherDataFromTimestamp(self, timestamp):
        hUrl = f"http://api.openweathermap.org/data/2.5/onecall/timemachine?lat={self.lat}&lon={self.lon}&dt={timestamp}&appid={self.key}"
        get = requests.get(hUrl)
        hWeather = json.loads(get.content)

        return hWeather

    def getWeatherNow(self):

        get = requests.get(self.url)
        data = json.loads(get.content)

        return data

    def getSolarPowerNow(self):

        data = self.getWeatherNow()

        cloudFactor = data["clouds"]["all"] / 100
        sunRiseUnix = data["sys"]["sunrise"]
        sunSetUnix = data["sys"]["sunset"]

        systemSize = 6000  #W
        maxCloudLoss = 0.30  #prosent

        currentTimeUnix = time.time()
        if currentTimeUnix > sunRiseUnix and currentTimeUnix < sunSetUnix:
            return systemSize * (1 - maxCloudLoss * cloudFactor)

        else:
            return 0
示例#7
0
        for hour in range(0, len(dataControl)):
            nowTemp = dataControl.loc[hour, 'startTime']
            if nowTemp.hour == 22 or nowTemp.hour == 23:  # reduce ventilation when going to bed
                dataControl.loc[hour, 'ventilation'] = True
            if dataControl.loc[hour, 'waterTempIncrease']:
                dataControl.loc[hour, 'ventilation'] = False
                dataControl.loc[hour, 'compressor'] = True
                dataControl.loc[hour, 'addHeating'] = True

                # ensure that heating is allowed in initial programm start
        if initial:
            for hour in range(0, 2):
                dataControl.loc[hour, 'compressor'] = True
                dataControl.loc[hour, 'addHeating'] = True
                dataControl.loc[hour, 'ventilation'] = False
        sunrise = sun.get_sunrise_time() + dt.timedelta(hours=utcoffset)
        sunset = sun.get_sunset_time() + dt.timedelta(hours=utcoffset)
        
        # plot dashboard
        # gererate axis label for for weather data    
        timeVecWeather = []
        timeVecWeatherLabel = []
        timeVecWeatherMinor = []
        timeVecWeatherLabel = []
        for hour in range(0, len(weatherData)):
            a = weatherData.loc[hour, 'start_time']
            if a.hour == 0:
                timeVecWeather.append(hour)
                timeVecWeatherLabel.append(
                    ' ' + a.strftime('%a') + ' ' + a.strftime('%d') + '.' + a.strftime('%m') + '.')
            if (weatherData.loc[hour, 'start_time'].hour / 3).is_integer():
示例#8
0
    apps = base + [
        'AppsUseLightTheme', '/t', 'REG_DWORD', '/d', values[1], '/f'
    ]
    windows = base + [
        'WindowsUseLightTheme', '/t', 'REG_DWORD', '/d', values[2], '/f'
    ]

    subprocess.run(system, stdout=subprocess.DEVNULL)
    subprocess.run(apps, stdout=subprocess.DEVNULL)
    subprocess.run(windows, stdout=subprocess.DEVNULL)


if __name__ == '__main__':
    # prepare for theme
    sun = Sun(45.4, 9.1)
    sunrise = sun.get_sunrise_time().strftime('%H:%M:%S')
    sunset = sun.get_sunset_time().strftime('%H:%M:%S')
    do_light, do_dark = True, True

    theme = {"light": ['1', '1', '0'], "dark": ['0', '0', '0']}

    # prepare for wallpapers
    path = r'{}\WallpaperEnhancer\Wallpapers'.format(os.environ['USERPROFILE'])
    files = os.listdir(path)
    images_str = [x.replace('.jpeg', '') for x in files]
    images = [int(x) for x in images_str]

    diff = [abs(x - int(get_time())) for x in images]
    first = str(images[diff.index(min(diff))])
    if len(first) == 5:
        first = '0' + first
示例#9
0
def get_sunlight_data(bbox,
                      center=DEFAULT_COORDS,
                      start_time='2016-09-28',
                      end_time='2019-09-28'):

    sun = Sun(center[1], center[0])

    for cc in range(0, 11, 1):
        wms_true_color_request = WmsRequest(
            layer='TRUE_COLOR',
            bbox=bbox,
            width=1000,
            height=1000,
            time=(start_time, end_time),
            maxcc=cc / 10,
            instance_id='0d1f2199-b4b9-4bad-b88b-8b2423e57b93')

        data = wms_true_color_request.get_dates()

        for date in data:
            sunrise = sun.get_sunrise_time(date)
            sunset = sun.get_sunset_time(date)

            suntime = (sunset - sunrise)
            suntime_hour = (sunset.hour - sunrise.hour)
            suntime_minute = (sunset.minute - sunrise.minute)

            sunrise_f = "%02d:%02d" % (sunrise.hour, sunrise.minute)
            sunset_f = "%02d:%02d" % (sunset.hour, sunset.minute)

            # print(sunrise_f)
            # print(sunset_f)
            suntime_number_uf = (int(suntime_hour) +
                                 round(int(suntime_minute) / 60, 2))
            suntime_number_f = '{:0>5.02f}'.format(suntime_number_uf)

            #print("number: ", suntime_number_uf)
            pw = ((suntime_number_uf * 0.2 * 1) +
                  (suntime_number_uf * 0.2 * 0.7) +
                  (suntime_number_uf * 0.3 * 0.4) +
                  (suntime_number_uf * 0.3 * 0.2)) * 1000

            real_cc = cc / 10
            if (real_cc < 0.31):
                kwh = pw * 1
            elif (real_cc >= 0.31 and real_cc < 0.71):
                kwh = pw * 0.6
            elif (real_cc >= 0.71 and real_cc < 0.91):
                kwh = pw * 0.3
            elif (real_cc >= 0.91):
                kwh = pw * 0.1

            sunlight_data.append([
                date, sunrise_f, sunset_f,
                "%d%%" % (cc * 10), suntime, suntime_number_f,
                round(pw),
                round(kwh)
            ])

    # print(sunlight_data)
    return remove_duplicates(sunlight_data)
示例#10
0
    def sun_time(self):

        sun_time = Sun(self.latlon_point.latitude, self.latlon_point.longitude)

        self.date = self.date + timedelta(days=self.date_increase)

        try:
            today_sunrise = sun_time.get_sunrise_time(self.date)
        except SunTimeException:
            if date(year=self.date.year, month=3, day=21)\
                    < self.date.date()\
                    < date(year=self.date.year, month=9, day=22):
                return 0, 360
            return 0, 0

        try:
            today_sunset = sun_time.get_sunset_time(self.date)
        except SunTimeException:
            if date(year=self.date.year, month=3, day=21)\
                    < self.date.date()\
                    < date(year=self.date.year, month=9, day=22):
                return 0, 360
            return 0, 0

        # This is *super* ugly, I'm sure we can find a more elegant way to do this
        now = datetime.utcnow() - timedelta(hours=0)
        today_sunrise = today_sunrise.replace(tzinfo=None)
        today_sunset = today_sunset.replace(tzinfo=None)

        # After Sunrise, after Sunset
        if now > today_sunrise and today_sunset:
            # Get timedelta for each
            today_sunrise = now - today_sunrise
            today_sunset = now - today_sunset

            # Convert timedelta into minutes and round
            today_sunrise = round(today_sunrise.seconds / 60)
            today_sunset = round(today_sunset.seconds / 60)

            # Convert minutes into angles
            today_sunrise = today_sunrise * 0.25
            today_sunset = today_sunset * 0.25

        # Before Sunrise, after Sunset
        elif now < today_sunrise and today_sunset:
            today_sunrise = today_sunrise - now
            today_sunset = today_sunset - now

            today_sunrise = round(today_sunrise.seconds / 60)
            today_sunset = round(today_sunset.seconds / 60)

            today_sunrise = 360 - (today_sunrise * 0.25)
            today_sunset = 360 - (today_sunset * 0.25)

        # After Sunrise, before Sunset
        else:
            today_sunrise = now - today_sunrise
            today_sunset = today_sunset - now

            today_sunrise = round(today_sunrise.seconds / 60)
            today_sunset = round(today_sunset.seconds / 60)

            today_sunrise = today_sunrise * 0.25
            today_sunset = 360 - (today_sunset * 0.25)

        return today_sunrise, today_sunset
示例#11
0
relay4 = 16
chan_list = (relay1, relay2, relay3, relay4)

# Making sure the first loop (on reboot/startup) will always update
lastMinute = 999
lastDay = 99

turnedOn = False

GPIO.setup(chan_list, GPIO.OUT)
GPIO.output(chan_list, GPIO.HIGH)

# Initial declaration necessary for global scope access
try:
    sun = Sun(latitude, longitude)
    sunrise = sun.get_sunrise_time()
    sunset = sun.get_sunset_time()
    # Version for machine's local time
    # sunrise = sun.get_local_sunrise_time()
    # sunset = sun.get_local_sunset_time()
    light_turnOn = sunset + timedelta(minutes=20)
    light_turnOn_time = time(light_turnOn.hour,
                             light_turnOn.minute,
                             tzinfo=tz.tzutc())
    light_turnOff = sunrise + timedelta(minutes=30)
    light_turnOff_time = time(light_turnOff.hour,
                              light_turnOff.minute,
                              tzinfo=tz.tzutc())
except SunTimeException as e:
    if debug:
        print("SunTime failed. Error: {0}.".format(e))
示例#12
0
#Getting the position of yesterday's date on the calender
dt = datetime.datetime.now()- datetime.timedelta(days=1)

#print(str(datetime.datetime.now()))

year = dt.year
month = dt.month
day = dt.day
hour = dt.hour

#Checking if it is day or night
latitude = 36.3504
longitude = 127.3845
sun = Sun(latitude, longitude)
sr_time = (sun.get_sunrise_time()+datetime.timedelta(hours=9)).time()
ss_time = (sun.get_sunset_time()+datetime.timedelta(hours=9)).time()
sr_hour = int(sr_time.hour)
ss_hour = int(ss_time.hour)
curr_time = datetime.datetime.now().time()
isDay = 0
if (sr_time < curr_time < ss_time):
    isDay = 1

#retrieving data
dict_param = {
    'yy': year,
    'mm': month,
    'dd': day,
    'hh': hour,
    'obs': 0
示例#13
0
config = configparser.ConfigParser()
config.read('/home/pi/coop/coop.ini')

# logging
logging.basicConfig(filename=config['Settings']['LogFile'],
                    level=config['Settings']['LogLevel'],
                    format='%(asctime)s - %(levelname)s: %(message)s')

# Suntime
sun = Sun(float(config['Location']['Latitude']),
          float(config['Location']['Longitude']))
now = (datetime.now(timezone.utc))
offset = int(config['Door']['Offset'])
doortime_open: int = int(config['Door']['Doortime_Open'])
doortime_close: int = int(config['Door']['Doortime_Close'])
opentime = sun.get_sunrise_time() - timedelta(minutes=offset)
closetime = sun.get_sunset_time() + timedelta(minutes=offset)
opentimetomorrow = sun.get_local_sunrise_time(datetime.now() +
                                              timedelta(days=1) -
                                              timedelta(minutes=offset))
closetimeyesterday = sun.get_local_sunset_time(datetime.now() + timedelta(
    days=-1)) + timedelta(minutes=offset)
global stop_threads

# GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
TopSensor = int(config['GPIO']['TopSensor'])
BottomSensor = int(config['GPIO']['BottomSensor'])
GPIO.setup(TopSensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(BottomSensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)
示例#14
0
    def __call__(self, i):
        self.sysStats = updateSysStats(self.sysStats)
        sysStatsX = extractSysStats(self.sysStats, 'time')
        #CPU percentage
        self.ax1.cla()
        self.ax1.update(self.ax1props)
        cpuPercent = extractSysStats(self.sysStats, 'cpuPercent')
        cpuColors = ['y', 'b', 'g', 'm']
        for idx, color in zip(range(4), cpuColors):
            self.ax1.bar(sysStatsX,
                         cpuPercent[idx],
                         width=2,
                         zs=idx,
                         zdir='y',
                         color=color * len(sysStatsX),
                         alpha=.8)
        #CPU temperature
        cpuTempCel = extractSysStats(self.sysStats, 'cpuTempCel')
        self.lines[1]['cpuTempCel'].set_data(sysStatsX, cpuTempCel)
        #memory percertange
        memPercent = extractSysStats(self.sysStats, 'memPercent')
        self.lines[1]['memPercent'].set_data(sysStatsX, memPercent)
        #globe
        if max(self.sysStats.keys()) > self.ax4TimeToUpdate:
            if max(self.sysStats.keys()) > self.ax4TimeToGeoLoc:
                try:
                    geolocResponse = self.http.request(
                        'GET', 'http://ipinfo.io/json')
                    geolocData = json.loads(geolocResponse.data)
                    self.ax4GeoLoc = eval(geolocData['loc'])[0:2]
                except:
                    self.ax4GeoLoc = self.ax4GeoLoc

            self.ax4.cla()
            self.ax4.set_global()
            self.ax4.coastlines()
            #             self.ax4.stock_img()
            #             self.ax4.background_img(name='BM', resolution='low')
            utcnow = datetime.utcnow()
            self.ax4.add_feature(Nightshade(utcnow, alpha=.15))
            scatterLongitudes = [x[1] for x in CitiesCoords.values()
                                 ]  #+[self.ax4GeoLoc[1]]
            scatterLatitudes = [x[0] for x in CitiesCoords.values()
                                ]  #+[self.ax4GeoLoc[0]]
            scatterColors = ['c'] * len(CitiesCoords)  #+['r']
            self.ax4.scatter(scatterLongitudes,
                             scatterLatitudes,
                             s=10,
                             c=scatterColors,
                             alpha=.8,
                             transform=ccrs.PlateCarree())
            self.ax4.gridlines(crs=ccrs.PlateCarree(),
                               xlocs=[self.ax4GeoLoc[1]],
                               ylocs=[self.ax4GeoLoc[0]],
                               color='y',
                               alpha=.4)
            self.ax4.plot([self.ax4GeoLoc[1]], [self.ax4GeoLoc[0]],
                          ms=7,
                          c='r',
                          transform=ccrs.PlateCarree(),
                          **{
                              'marker': '$\\bigoplus$',
                              'linestyle': '',
                              'markeredgewidth': .1
                          })
            for (k, v) in CitiesCoords.items():
                self.ax4.text(v[1] + 3,
                              v[0] - 3,
                              k,
                              fontsize='xx-small',
                              color='b',
                              alpha=.95,
                              horizontalalignment='left',
                              verticalalignment='top',
                              transform=ccrs.Geodetic())
            sun = Sun(self.ax4GeoLoc[0], self.ax4GeoLoc[1])
            today = utcnow.date()
            sunrises = [
                sun.get_sunrise_time(d) for d in
                [today - timedelta(days=1), today, today + timedelta(days=1)]
            ]
            sunsets = [
                sun.get_sunset_time(d) for d in
                [today - timedelta(days=1), today, today + timedelta(days=1)]
            ]
            sunTimes = sunrises + sunsets
            sunTimes = [d.replace(tzinfo=None) for d in sunTimes]
            sunTimes.sort()
            sunTimeLast = [
                t for t in sunTimes if t < utcnow.replace(tzinfo=None)
            ][-1]
            sunTimeNext = [
                t for t in sunTimes if t >= utcnow.replace(tzinfo=None)
            ][0]
            sunHoursDeltas = [t - utcnow for t in [sunTimeLast, sunTimeNext]]
            sunHours = [
                td.days * 24 + td.seconds / 3600 for td in sunHoursDeltas
            ]
            sunHHMMs = [
                '{:+03.0f}:{:02.0f}'.format(math.trunc(sh),
                                            60 * abs(sh - math.trunc(sh)))
                for sh in sunHours
            ]
            meStrTxts = [
                self.ax4.text(self.ax4GeoLoc[1] + txtPosShiftHor,
                              self.ax4GeoLoc[0] + 3,
                              meStr,
                              fontsize='xx-small',
                              fontweight='normal',
                              color='m',
                              alpha=.99,
                              horizontalalignment=txtPosAlignHor,
                              transform=ccrs.Geodetic())
                for (meStr, txtPosAlignHor, txtPosShiftHor
                     ) in zip(sunHHMMs, ['right', 'left'], [-3, 3])
            ]
            for txtObj in meStrTxts:
                txtObj.set_path_effects(
                    [PathEffects.withStroke(linewidth=2, foreground='w')])
            self.ax4TimeToUpdate += timedelta(seconds=300)
            self.ax4TimeToGeoLoc += timedelta(seconds=1200)
示例#15
0
import datetime
from suntime import Sun, SunTimeException
from datetime import datetime
from dateutil import tz

# Auto-detect timezones
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# Felton, CA 37.0513° N, 122.0733° W
city_name = "Felton, CA"
latitude = 37.0513
longitude = -122.0733

sun = Sun(latitude, longitude)

# Get today's sunrise and sunset in UTC
today_sr_utc = sun.get_sunrise_time()
today_sr_local = sun.get_local_sunrise_time()
today_ss_utc = sun.get_sunset_time()
today_ss_local = sun.get_local_sunset_time()

print('Today at {} the sun rose at {} and goes down at {} UTC'.format(
    city_name, today_sr_utc.strftime('%H:%M'), today_ss_utc.strftime('%H:%M')))
print('Today at {} the sun rose at {} and goes down at {} localtime'.format(
    city_name, today_sr_local.strftime('%H:%M'),
    today_ss_local.strftime('%H:%M')))