• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python astral.Astral类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中astral.Astral的典型用法代码示例。如果您正苦于以下问题:Python Astral类的具体用法?Python Astral怎么用?Python Astral使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Astral类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: getCorrectBackground

	def getCorrectBackground(self):
		if self.Weather == None:
			return "day-sunny"
		
		city_name = 'London'
		a = Astral()
		a.solar_depression = 'civil'
		city = a[city_name]
		now = datetime.datetime.utcnow().replace(tzinfo=utc)
		sun = city.sun(date=datetime.datetime.now(), local=True)
		
		if now < sun['dawn']:
			#night
			return self.getNightBackground()
		elif now < sun['sunrise']:
			#sunrise
			return self.getSunSetRiseBackground()
		elif now < sun['sunset']:
			#day
			return self.getDayBackground()
		elif now < sun['dusk']:
			#sunset
			return self.getSunSetRiseBackground()
		else:
			#night
			return self.getNightBackground()
开发者ID:Tomcuzz,项目名称:OctaHomeAutomation,代码行数:26,代码来源:views.py


示例2: ics

def ics():
    astral = Astral()
    astral.solar_depression = "civil"
    astral.depression = 6.0

    city = astral["Toronto"]

    cal = Calendar()
    cal.add("prodid", "-//Time of Day//time-of-day.herokuapp.com//")
    cal.add("version", "2.0")

    today = datetime.date.today()

    for x in range(-7, 8):
        date = today + datetime.timedelta(days=x)

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

        for summary, time in sun.items():
            event = Event()
            event.add("summary", summary.capitalize())
            event.add("dtstart", time)
            event.add("dtend", time)
            event.add("dtstamp", time)

            cal.add_component(event)

    resp = make_response(cal.to_ical())

    resp.headers["Content-Disposition"] = "attachment; filename=time-of-day.ics"
    resp.headers["Content-Type"] = "text/calendar"

    return resp
开发者ID:myles,项目名称:time-of-day,代码行数:33,代码来源:views.py


示例3: get_astral_data

def get_astral_data(for_datetime):
    '''
    Returns the sunrise and sunset times for the given date.
    Uses the Astral package to compute sunrise/sunset for the
    configured city.
    Reference https://pythonhosted.org/astral/module.html
    :param for_datetime:
    :return: Returns a dict containing the keys sunrise and sunset.
    The values are datetime objects.
    '''
    a = Astral()
    a.solar_depression = "civil"
    # We use a city just to get a city object. Then we override the lat/long.
    # The city object can produce sunrise/sunset in local time.
    if Configuration.City() != "":
        city = a[Configuration.City()]
    else:
        # Default if no city is configured
        city = a["New York"]
    if Configuration.Latitude() != "":
        city.latitude = float(Configuration.Latitude())
    if Configuration.Longitude() != "":
        city.longitude = float(Configuration.Longitude())

    return city.sun(date=for_datetime, local=True)
开发者ID:dhocker,项目名称:ahps_web,代码行数:25,代码来源:sun_data.py


示例4: __init__

 def __init__(self):
     self.hardware = Hardware()
     a = Astral()
     a.solar_depression = 'civil'
     self.city = a['Kiev']
     self.rpc_server = RPCServer(self.hardware) 
     self.rpc_server.start()
开发者ID:sheinz,项目名称:flower-pi,代码行数:7,代码来源:FlowerPi.py


示例5: seconds_till_daytime_ends

def seconds_till_daytime_ends(lat,lon,delta_minutes):
   if not is_it_daytime(lat,lon,delta_minutes):
       return 0
   now = datetime.now(UTC())
   astral = Astral()
   sunset = astral.sunset_utc(now,lat,lon) - timedelta(minutes=delta_minutes)
   answer = int((sunset-now).total_seconds())+1
   return answer
开发者ID:IrishMarineInstitute,项目名称:uwobs,代码行数:8,代码来源:daytimes.py


示例6: getSolarInfo

def getSolarInfo():
    a = Astral()
    a.solar_depression = 'civil'
    city = a['Seattle']
    timezone = city.timezone
    sun = city.sun(date=datetime.datetime.now())

    return sun
开发者ID:brianco,项目名称:HomeAutomation,代码行数:8,代码来源:HomeAutomation.py


示例7: __init__

class plugin:
    '''
    A class to display the time of sunrise/sunset
    Uses the astral library to retrieve information...
    '''

    def __init__(self, config):
        '''
        Initializations for the startup of the weather forecast
        '''
        # Get plugin name (according to the folder, it is contained in)
        self.name = os.path.dirname(__file__).split('/')[-1]

        self.astral_at_location = Astral()[config.get('plugin_' + self.name, 'location')]

        # Choose language to display sunrise
        language = config.get('plugin_time_default', 'language')
        if language == 'german':
            self.taw = wcp_time_german.time_german()
        elif language == 'dutch':
            self.taw = wcp_time_dutch.time_dutch()
        elif language == 'swiss_german':
            self.taw = wcp_swiss_german.time_swiss_german()
        else:
            print('Could not detect language: ' + language + '.')
            print('Choosing default: german')
            self.taw = wcp_time_german.time_german()

        self.bg_color_index     = 0 # default background color: black
        self.word_color_index   = 2 # default word color: warm white
        self.minute_color_index = 2 # default minute color: warm white

    def run(self, wcd, wci):
        '''
        Displaying current time for sunrise/sunset
        '''
        # Get data of sunrise
        sun_data = self.astral_at_location.sun(date=datetime.datetime.now(), local=True)
        # Display data of sunrise
        wcd.animate(self.name, 'sunrise', invert=True)
        wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True)
        taw_indices = self.taw.get_time(sun_data['sunrise'], withPrefix=False)
        wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index])
        wcd.show()
        time.sleep(3)
        # Display data of sunset
        wcd.animate(self.name, 'sunrise')
        wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True)
        taw_indices = self.taw.get_time(sun_data['sunset'], withPrefix=False)
        wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index])
        wcd.show()
        time.sleep(3)
        # Display current moon phase
        moon_phase = int(self.astral_at_location.moon_phase(datetime.datetime.now()))
        for i in range(0, moon_phase):
            wcd.showIcon('sunrise', 'moon_'+str(i).zfill(2))
            time.sleep(0.1)
        time.sleep(3)
开发者ID:dgeordgy21,项目名称:rpi_wordclock,代码行数:58,代码来源:plugin.py


示例8: test_track_sunset

    def test_track_sunset(self):
        """Test track the sunset."""
        latitude = 32.87336
        longitude = 117.22743

        # Setup sun component
        self.hass.config.latitude = latitude
        self.hass.config.longitude = longitude
        setup_component(self.hass, sun.DOMAIN, {
            sun.DOMAIN: {sun.CONF_ELEVATION: 0}})

        # Get next sunrise/sunset
        astral = Astral()
        utc_now = datetime(2014, 5, 24, 12, 0, 0, tzinfo=dt_util.UTC)
        utc_today = utc_now.date()

        mod = -1
        while True:
            next_setting = (astral.sunset_utc(
                utc_today + timedelta(days=mod), latitude, longitude))
            if next_setting > utc_now:
                break
            mod += 1

        # Track sunset
        runs = []
        with patch('homeassistant.util.dt.utcnow', return_value=utc_now):
            unsub = track_sunset(self.hass, lambda: runs.append(1))

        offset_runs = []
        offset = timedelta(minutes=30)
        with patch('homeassistant.util.dt.utcnow', return_value=utc_now):
            unsub2 = track_sunset(
                self.hass, lambda: offset_runs.append(1), offset)

        # Run tests
        self._send_time_changed(next_setting - offset)
        self.hass.block_till_done()
        self.assertEqual(0, len(runs))
        self.assertEqual(0, len(offset_runs))

        self._send_time_changed(next_setting)
        self.hass.block_till_done()
        self.assertEqual(1, len(runs))
        self.assertEqual(0, len(offset_runs))

        self._send_time_changed(next_setting + offset)
        self.hass.block_till_done()
        self.assertEqual(1, len(runs))
        self.assertEqual(1, len(offset_runs))

        unsub()
        unsub2()

        self._send_time_changed(next_setting + offset)
        self.hass.block_till_done()
        self.assertEqual(1, len(runs))
        self.assertEqual(1, len(offset_runs))
开发者ID:tmcarr,项目名称:home-assistant,代码行数:58,代码来源:test_event.py


示例9: graph_values

def graph_values(diff_array):
    graph_data = []
    graph_dates = []
    sum_value = 0
    index = 0
    current_hour = plot_dates[0].hour
    sun_indexes = []

    city_name = 'Stockholm'
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]

    sun = city.sun(plot_dates[0], local=True)

    graph_dates.append(plot_dates[0].strftime('%Y-%m-%d %H:%M:%S'))

    if (plot_dates[index].hour >= sun['sunrise'].hour and
            plot_dates[index].hour <= sun['sunset'].hour):
        sun_indexes.append(1)
    else:
        sun_indexes.append(0)

    for data in diff_array:
        if (plot_dates[index].hour > current_hour):
            graph_data.append(sum_value)
            sum_value = 0
            sum_value = sum_value + int(data)
            current_hour = current_hour + 1

            if (plot_dates[index].hour >= sun['sunrise'].hour and
                    plot_dates[index].hour <= sun['sunset'].hour):
                sun_indexes.append(1)
            else:
                sun_indexes.append(0)

            graph_dates.append(plot_dates[index].strftime('%Y-%m-%d %H:%M:%S'))
        elif (plot_dates[index].hour < current_hour):
            graph_data.append(sum_value)
            sum_value = 0
            sum_value = sum_value + int(data)
            current_hour = plot_dates[index].hour
            sun = city.sun(plot_dates[index], local=True)
            if (plot_dates[index].hour >= sun['sunrise'].hour and
                    plot_dates[index].hour <= sun['sunset'].hour):
                sun_indexes.append(1)
            else:
                sun_indexes.append(0)

            graph_dates.append(plot_dates[index].strftime('%Y-%m-%d %H:%M:%S'))
        else:
            sum_value = sum_value + int(data)

        index = index + 1

    graph_data.append(sum_value)

    return graph_dates, graph_data, sun_indexes
开发者ID:Drotth,项目名称:NUMA01,代码行数:58,代码来源:project_3_birds.py


示例10: seconds_till_daytime

def seconds_till_daytime(lat,lon,delta_minutes):
   if is_it_daytime(lat,lon,delta_minutes):
       return 0
   now = datetime.now(UTC())
   astral = Astral()
   sunrise = astral.sunrise_utc(now,lat,lon) + timedelta(minutes=delta_minutes)
   if sunrise < now:
      sunrise = astral.sunrise_utc(now + timedelta(hours=23),lat,lon) + timedelta(minutes=delta_minutes)
   return int((sunrise-now).total_seconds())+1
开发者ID:IrishMarineInstitute,项目名称:uwobs,代码行数:9,代码来源:daytimes.py


示例11: get_sun

def get_sun(date="today", depression="astronomical", cityname="Boston"):
    astral = Astral()
    astral.solar_depression = depression
    city = astral[cityname]
    calendar = parsedatetime.Calendar()
    dateinfo = calendar.parse(date)
    date_ts = time.mktime(dateinfo[0])
    date_dt = datetime.fromtimestamp(date_ts)
    return city.sun(date=date_dt, local=True)
开发者ID:vishnubob,项目名称:obscura,代码行数:9,代码来源:timelapse.py


示例12: api_v1

def api_v1():
    astral = Astral()
    astral.solar_depression = "civil"
    astral.depression = 6.0

    city = astral["Toronto"]

    response = {
        "is_day": False,
        "is_night": False,
        "is_civil_twlight": False,
        "is_nautical_twlight": False,
        "is_astronomical_twilight": False,
        "is_blue_hour": False,
        "is_golden_hour": False,
        "solar_zenith_angle": city.solar_zenith(),
        "solar_elevation_angle": city.solar_elevation(),
        "solar_azimuth_angle": city.solar_azimuth(),
        "times_of_day": city.sun(),
    }

    current_datetime = datetime.datetime.now(city.tz)

    if city.sunrise() < current_datetime < city.sunset():
        response["is_day"] = True
    else:
        response["is_night"] = True

    if -6 <= city.solar_zenith() <= 0:
        response["is_civil_twlight"] = True
        response["is_day"] = False
        response["is_night"] = False
    elif -12 <= city.solar_zenith() <= -6:
        response["is_nautical_twlight"] = True
        response["is_day"] = False
        response["is_night"] = False
    elif -18 <= city.solar_zenith() <= -12:
        response["is_astronomical_twilight"] = True
        response["is_day"] = False
        response["is_night"] = False

    if -6 <= city.solar_zenith() <= -4:
        response["is_blue_hour"] = True
    elif -4 <= city.solar_zenith() <= 6:
        response["is_golden_hour"] = True

    if 0 <= city.moon_phase() < 7:
        response["moon_phase"] = "new-moon"
    elif 7 <= city.moon_phase() < 14:
        response["moon_phase"] = "first-quarter"
    elif 14 <= city.moon_phase() < 21:
        response["moon_phase"] = "full-moon"
    elif 21 <= city.moon_phase():
        response["moon_phase"] = "last-quarter"

    return jsonify(response)
开发者ID:myles,项目名称:time-of-day,代码行数:56,代码来源:views.py


示例13: testElevation

def testElevation():
    city_name = "Jubail"

    dd = Astral()
    city = dd[city_name]

    dt = datetime.datetime.now(tz=city.tz)
    print("Date & time: %s" % dt)
    print("Date & time (UTC): %s" % dt.astimezone(pytz.utc))
    print("Elevation: %.02f" % dd.solar_elevation(dt, city.latitude, city.longitude))
开发者ID:aman-thakral,项目名称:astral,代码行数:10,代码来源:testAstral.py


示例14: its_after_sunset

def its_after_sunset(city_name):
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=date.today(), local=True)
    sunset_today = (sun['sunset']).replace(tzinfo=None)
    if sunset_today < datetime.today():
        return True
    else:
        return False
开发者ID:umarsear,项目名称:solar-energy-notification,代码行数:10,代码来源:sun_stage.py


示例15: test_track_sunrise

    def test_track_sunrise(self):
        """Test track the sunrise."""
        latitude = 32.87336
        longitude = 117.22743

        # Setup sun component
        self.hass.config.latitude = latitude
        self.hass.config.longitude = longitude
        setup_component(self.hass, sun.DOMAIN, {
            sun.DOMAIN: {sun.CONF_ELEVATION: 0}})

        # Get next sunrise/sunset
        astral = Astral()
        utc_now = dt_util.utcnow()

        mod = -1
        while True:
            next_rising = (astral.sunrise_utc(utc_now +
                           timedelta(days=mod), latitude, longitude))
            if next_rising > utc_now:
                break
            mod += 1

        # Track sunrise
        runs = []
        unsub = track_sunrise(self.hass, lambda: runs.append(1))

        offset_runs = []
        offset = timedelta(minutes=30)
        unsub2 = track_sunrise(self.hass, lambda: offset_runs.append(1),
                               offset)

        # run tests
        self._send_time_changed(next_rising - offset)
        self.hass.block_till_done()
        self.assertEqual(0, len(runs))
        self.assertEqual(0, len(offset_runs))

        self._send_time_changed(next_rising)
        self.hass.block_till_done()
        self.assertEqual(1, len(runs))
        self.assertEqual(0, len(offset_runs))

        self._send_time_changed(next_rising + offset)
        self.hass.block_till_done()
        self.assertEqual(2, len(runs))
        self.assertEqual(1, len(offset_runs))

        unsub()
        unsub2()

        self._send_time_changed(next_rising + offset)
        self.hass.block_till_done()
        self.assertEqual(2, len(runs))
        self.assertEqual(1, len(offset_runs))
开发者ID:DavidLP,项目名称:home-assistant,代码行数:55,代码来源:test_event.py


示例16: its_between_dawn_sunset

def its_between_dawn_sunset(city_name):
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=date.today(), local=True)
    dawn_today = (sun['dawn']).replace(tzinfo=None)
    sunset_today = (sun['sunset']).replace(tzinfo=None)
    if (dawn_today < datetime.today()) and (sunset_today > datetime.today()):
        return True
    else:
        return False
开发者ID:umarsear,项目名称:solar-energy-notification,代码行数:11,代码来源:sun_stage.py


示例17: testAzimuth

def testAzimuth():
    city_name = "Jubail"

    dd = Astral()
    city = dd[city_name]
    print("Latitude: %f, Longitude: %f" % (city.latitude, city.longitude))

    dt = datetime.datetime.now(tz=city.tz)
    print("Date & time: %s" % dt)
    print("Date & time (UTC): %s" % dt.astimezone(pytz.utc))
    print("Azimuth: %.02f" % dd.solar_azimuth(dt, city.latitude, city.longitude))
开发者ID:aman-thakral,项目名称:astral,代码行数:11,代码来源:testAstral.py


示例18: its_light_in

def its_light_in(city_name):
    a = Astral()
    a.solar_depression = 'civil'
    city = a[city_name]
    sun = city.sun(date=date.today(), local=True)
    dawn_today = (sun['dawn']).replace(tzinfo=None)

    if dawn_today < datetime.today():
        return True
    else:
        return False
开发者ID:umarsear,项目名称:solar-energy-notification,代码行数:11,代码来源:sun_stage.py


示例19: daytime

def daytime():
    """
    Compute whether it is currently daytime based on current location
    """
    city = Astral()[CITY]
    sundata = city.sun()

    sunrise = sundata['sunrise'] + timedelta(minutes=DELTA)
    sunset = sundata['sunset'] - timedelta(minutes=DELTA)
    now = datetime.now(sunrise.tzinfo)

    return sunrise < now < sunset
开发者ID:danallan,项目名称:shue-server,代码行数:12,代码来源:home.py


示例20: main

def main():
	a = Astral()
	a.solar_depression = 'civil'
	city = a['Birmingham']
	timezone = city.timezone
	sun = city.sun(date=datetime.date.today(), local=True)
	if is_light_outside(sun['dawn'], sun['dusk']):
		logger.info("Its light outside, switching off...")
		switch_off()
	else:
		logger.info("Its dark outside, switching on...")
		switch_on()
开发者ID:bwghughes,项目名称:homeautomation,代码行数:12,代码来源:job.py



注:本文中的astral.Astral类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python plotting.hist函数代码示例发布时间:2022-05-24
下一篇:
Python astra.create_vol_geom函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap