Python datetime.date() Examples

The following are 30 code examples for showing how to use datetime.date(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: aospy   Author: spencerahill   File: times.py    License: Apache License 2.0 6 votes vote down vote up
def datetime_or_default(date, default):
    """Return a datetime-like object or a default.

    Parameters
    ----------
    date : `None` or datetime-like object or str
    default : The value to return if `date` is `None`

    Returns
    -------
    `default` if `date` is `None`, otherwise returns the result of
    `utils.times.ensure_datetime(date)`

    """
    if date is None:
        return default
    else:
        return ensure_datetime(date) 
Example 2
Project: wechatpy   Author: wechatpy   File: tools.py    License: MIT License 6 votes vote down vote up
def download_bill(self, bill_date, bill_type="ALL", device_info=None):
        """
        下载对账单

        :param bill_date: 下载对账单的日期
        :param bill_type: 账单类型,ALL,返回当日所有订单信息,默认值
                          SUCCESS,返回当日成功支付的订单,
                          REFUND,返回当日退款订单,
                          REVOKED,已撤销的订单
        :param device_info: 微信支付分配的终端设备号,填写此字段,只下载该设备号的对账单
        :return: 返回的结果数据
        """
        if isinstance(bill_date, (datetime, date)):
            bill_date = bill_date.strftime("%Y%m%d")

        data = {
            "appid": self.appid,
            "bill_date": bill_date,
            "bill_type": bill_type,
            "device_info": device_info,
        }
        return self._post("pay/downloadbill", data=data) 
Example 3
Project: wechatpy   Author: wechatpy   File: tools.py    License: MIT License 6 votes vote down vote up
def download_fundflow(self, bill_date, account_type="Basic", tar_type=None):
        """
        下载资金账单
        https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_18&index=7

        :param bill_date: 下载对账单的日期
        :param account_type: 账单的资金来源账户
                             Basic  基本账户
                             Operation 运营账户
                             Fees 手续费账户
        :param tar_type: 非必传参数,固定值:GZIP,返回格式为.gzip的压缩包账单。
                         不传则默认为数据流形式。
        """
        if isinstance(bill_date, (datetime, date)):
            bill_date = bill_date.strftime("%Y%m%d")

        data = {
            "appid": self.appid,
            "bill_date": bill_date,
            "account_type": account_type,
            "sign_type": "HMAC-SHA256",
        }
        if tar_type is not None:
            data["tar_type"] = tar_type
        return self._post("pay/downloadfundflow", data=data) 
Example 4
Project: wechatpy   Author: wechatpy   File: wifi.py    License: MIT License 6 votes vote down vote up
def list_statistics(self, begin_date, end_date, shop_id=-1):
        """
        Wi-Fi数据统计

        详情请参考
        http://mp.weixin.qq.com/wiki/8/dfa2b756b66fca5d9b1211bc18812698.html

        :param begin_date: 起始日期时间,最长时间跨度为30天
        :param end_date: 结束日期时间戳,最长时间跨度为30天
        :param shop_id: 可选,门店 ID,按门店ID搜索,-1为总统计
        :return: 返回的 JSON 数据包
        """
        if isinstance(begin_date, (datetime, date)):
            begin_date = begin_date.strftime("%Y-%m-%d")
        if isinstance(end_date, (datetime, date)):
            end_date = end_date.strftime("%Y-%m-%d")
        res = self._post(
            "statistics/list",
            data={"begin_date": begin_date, "end_date": end_date, "shop_id": shop_id},
            result_processor=lambda x: x["data"],
        )
        return res 
Example 5
Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def get_available_rooms():
    campus = request.args.get('campus')
    building = request.args.get('building')
    time = request.args.get('time')
    date_str = request.args.get('date')
    if not date_str:
        date = datetime.date.today()
    else:
        date = datetime.date(*map(int, date_str.split('-')))

    # vip 可以选择日期,普通用户只能选择时间

    if not campus:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'missing campus parameter')
    if not building:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'missing building parameter')
    if not time:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'missing time parameter')

    return generate_success_response(entity_service.get_available_rooms(campus, building, date, time)) 
Example 6
Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def report_unavailable_room():
    room_id_encoded = request.args.get("room_id")
    time = request.args.get("time")
    date_str = request.args.get("date")
    date = datetime.date(*map(int, date_str.split('-')))

    # 运营策略:报告获得他人认同可以加积分

    if not room_id_encoded:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'missing room_id parameter')
    if not time:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'missing time parameter')
    if not date_str:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'missing date parameter')

    try:
        resource_type, room_id = decrypt(room_id_encoded, resource_type=RTYPE_ROOM)
    except ValueError:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, 'invalid room_id')

    entity_service.report_unavailable_room(room_id, date, time, *get_ut_uid())
    return generate_success_response(None) 
Example 7
Project: everyclass-server   Author: everyclass   File: domain.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def get_semester_date(date: datetime.date) -> Tuple[str, int, int]:
    """获取日期对应的学期、所属周次及星期(0表示周日,1表示周一...)

    >>> get_semester_date(datetime.date(2020, 2, 22))
    ('2019-2020-1', 26, 6)

    >>> get_semester_date(datetime.date(2020, 2, 23))
    ('2019-2020-2', 1, 0)
    """
    config = get_config()

    semesters = list(config.AVAILABLE_SEMESTERS.items())
    semesters.sort(key=lambda x: x[0], reverse=True)

    for sem in semesters:
        sem_start_date = datetime.date(*sem[1]["start"])
        if date >= sem_start_date:
            days_delta = (date - sem_start_date).days
            return "-".join([str(x) for x in sem[0]]), days_delta // 7 + 1, days_delta % 7
    raise ValueError("no applicable semester") 
Example 8
Project: pypika   Author: kayak   File: terms.py    License: Apache License 2.0 6 votes vote down vote up
def get_value_sql(self, **kwargs: Any) -> str:
        quote_char = kwargs.get("secondary_quote_char") or ""

        # FIXME escape values
        if isinstance(self.value, Term):
            return self.value.get_sql(**kwargs)
        if isinstance(self.value, Enum):
            return self.value.value
        if isinstance(self.value, date):
            value = self.value.isoformat()
            return format_quotes(value, quote_char)
        if isinstance(self.value, str):
            value = self.value.replace(quote_char, quote_char * 2)
            return format_quotes(value, quote_char)
        if isinstance(self.value, bool):
            return str.lower(str(self.value))
        if self.value is None:
            return "null"
        return str(self.value) 
Example 9
Project: wuy   Author: manatlan   File: test_json.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_json():
    def test(j, testType=None):
        def testSUS(obj, testType=None):
            s = wuy.jDumps(obj)
            nobj = wuy.jLoads(s)
            assert type(nobj) == testType

        testSUS(dict(v=j), dict)
        testSUS([j, dict(a=[j])], list)
        testSUS(j, testType)

    class Ob:
        def __init__(self):
            self.name = "koko"

    test(datetime.now(), datetime)
    test(date(1983, 5, 20), datetime)
    test(b"kkk", str)
    test("kkk", str)
    test(42, int)
    test(4.2, float)
    test(None, type(None))
    test(Ob(), dict)
    test(datetime.now() - datetime.now(), str) 
Example 10
Project: pywr   Author: pywr   File: test_parameters.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_parameter_array_indexed_json_load(simple_linear_model, tmpdir):
    """Test ArrayIndexedParameter can be loaded from json dict"""
    model = simple_linear_model
    # Daily time-step
    index = pd.date_range('2015-01-01', periods=365, freq='D', name='date')
    df = pd.DataFrame(np.arange(365), index=index, columns=['data'])
    df_path = tmpdir.join('df.csv')
    df.to_csv(str(df_path))

    data = {
        'type': 'arrayindexed',
        'url': str(df_path),
        'index_col': 'date',
        'parse_dates': True,
        'column': 'data',
    }

    p = load_parameter(model, data)
    model.setup()

    si = ScenarioIndex(0, np.array([0], dtype=np.int32))
    for v, ts in enumerate(model.timestepper):
        np.testing.assert_allclose(p.value(ts, si), v) 
Example 11
Project: pywr   Author: pywr   File: test_parameters.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_parameter_df_json_load(model, tmpdir):

    # Daily time-step
    index = pd.date_range('2015-01-01', periods=365, freq='D', name='date')
    df = pd.DataFrame(np.random.rand(365), index=index, columns=['data'])
    df_path = tmpdir.join('df.csv')
    df.to_csv(str(df_path))

    data = {
        'type': 'dataframe',
        'url': str(df_path),
        'index_col': 'date',
        'parse_dates': True,
    }

    p = load_parameter(model, data)
    p.setup() 
Example 12
Project: pywr   Author: pywr   File: test_parameters.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_parameter_df_embed_load(model):

    # Daily time-step
    index = pd.date_range('2015-01-01', periods=365, freq='D', name='date')
    df = pd.DataFrame(np.random.rand(365), index=index, columns=['data'])

    # Save to JSON and load. This is the format we support loading as embedded data
    df_data = df.to_json(date_format="iso")
    # Removing the time information from the dataset for testing purposes
    df_data = df_data.replace('T00:00:00.000Z', '')
    df_data = json.loads(df_data)

    data = {
        'type': 'dataframe',
        'data': df_data,
        'parse_dates': True,
    }

    p = load_parameter(model, data)
    p.setup() 
Example 13
Project: pywr   Author: pywr   File: test_parameters.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_current_ordinal_threshold_parameter(self, simple_linear_model):
        """Test CurrentYearThresholdParameter"""
        m = simple_linear_model

        m.timestepper.start = '2020-01-01'
        m.timestepper.end = '2030-01-01'

        threshold = datetime.date(2025, 6, 15).toordinal()

        data = {
            'type': 'currentordinaldaythreshold',
            'threshold': threshold,
            "predicate": ">=",
        }

        p = load_parameter(m, data)

        @assert_rec(m, p, get_index=True)
        def expected_func(timestep, scenario_index):
            o = timestep.datetime.toordinal()
            value = 1 if o >= threshold else 0
            return value

        m.run() 
Example 14
Project: figures   Author: appsembler   File: test_metrics.py    License: MIT License 6 votes vote down vote up
def test_get_total_site_users_for_time_period(self):
        '''
        TODO: add users who joined before and after the time period, and
        compare the count to the users created on or before the end date

        TODO: Create
        '''
        users = create_users_joined_over_time(
            site=self.site,
            is_multisite=figures.helpers.is_multisite(),
            start_date=self.data_start_date,
            end_date=self.data_end_date)
        count = get_total_site_users_for_time_period(
            site=self.site,
            start_date=self.data_start_date,
            end_date=self.data_end_date)
        assert count == len(users) 
Example 15
Project: figures   Author: appsembler   File: test_metrics.py    License: MIT License 6 votes vote down vote up
def test_get_total_site_users_for_time_period(self):
        '''
        TODO: add users who joined before and after the time period, and
        compare the count to the users created on or before the end date

        TODO: Create
        '''
        users = create_users_joined_over_time(
            site=self.alpha_site,
            is_multisite=figures.helpers.is_multisite(),
            start_date=self.data_start_date,
            end_date=self.data_end_date)
        count = get_total_site_users_for_time_period(site=self.alpha_site,
                                                     start_date=self.data_start_date,
                                                     end_date=self.data_end_date)
        assert count == len(users) 
Example 16
Project: figures   Author: appsembler   File: test_site_monthly_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_create(self):

        assert not SiteMonthlyMetrics.objects.count()
        year = 2020
        month = 4

        rec = dict(
            site=self.site,
            year=year,
            month=month,
            active_user_count=42,
        )
        expected_month_for = date(year=year, month=month, day=1)
        metrics, created = SiteMonthlyMetrics.add_month(**rec)
        assert metrics and created
        assert metrics.month_for == expected_month_for
        assert metrics.active_user_count == rec['active_user_count'] 
Example 17
Project: figures   Author: appsembler   File: test_course_daily_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_get_or_create(self):
        '''Sanity check we can create the SiteDailyMetrics model

        Create a second instance the way we'll do it in the production code.
        Assert this is correct
        '''
        rec = dict(
            site=self.site,
            date_for=datetime.date(2018, 2, 2),
            course_id='course-v1:SomeOrg+ABC01+2121',
            defaults=dict(
                enrollment_count=11,
                active_learners_today=1,
                average_progress=0.5,
                average_days_to_complete=5,
                num_learners_completed=10
            ),
        )
        metrics, created = CourseDailyMetrics.objects.get_or_create(**rec)
        assert metrics and created
        metrics2, created = CourseDailyMetrics.objects.get_or_create(**rec)
        assert metrics2 and not created
        assert metrics2 == metrics 
Example 18
Project: figures   Author: appsembler   File: test_course_daily_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_with_invalid_average_progress(self, average_progress):
        """
        Apparently Django models don't validate automatically on save
        """
        assert average_progress < 0 or average_progress > 1
        rec = dict(
            site=self.site,
            date_for=datetime.date(2018, 2, 2),
            course_id='course-v1:SomeOrg+ABC01+2121',
            enrollment_count=11,
            active_learners_today=1,
            average_progress=average_progress,
            average_days_to_complete=5,
            num_learners_completed=10
        )
        obj = CourseDailyMetrics(**rec)
        with pytest.raises(ValidationError) as execinfo:
            obj.clean_fields()

        assert 'average_progress' in execinfo.value.message_dict 
Example 19
Project: figures   Author: appsembler   File: test_course_daily_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_with_valid_average_progress(self, average_progress):
        """
        Average progress must be between 0.0 and 1.0 inclusive and no more than 2 decimal places
        """

        rec =  dict(
            site=self.site,
            date_for=datetime.date(2018, 2, 2),
            course_id='course-v1:SomeOrg+ABC01+2121',
            enrollment_count=11,
            active_learners_today=1,
            average_progress=str(average_progress),
            average_days_to_complete=5,
            num_learners_completed=10
        )
        metrics = CourseDailyMetrics.objects.create(**rec)
        assert metrics.average_progress == average_progress
        metrics.clean_fields() 
Example 20
Project: figures   Author: appsembler   File: test_course_daily_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_create_violates_unique(self, ):
        '''Test CourseDailyMetrics unique constraints
        First create a model instance, then try creating with the same
        date_for and course_id. It should raise IntegrityError
        '''

        rec = dict(
            site=self.site,
            date_for=datetime.date(2018, 2, 2),
            course_id='course-v1:SomeOrg+ABC01+2121',
            enrollment_count=11,
            active_learners_today=1,
            average_progress=0.5,
            average_days_to_complete=5,
            num_learners_completed=10
        )
        metrics = CourseDailyMetrics.objects.create(**rec)
        with pytest.raises(IntegrityError) as e_info:
            metrics = CourseDailyMetrics.objects.create(**rec)
            assert e_info.value.message.startswith('UNIQUE constraint failed') 
Example 21
Project: figures   Author: appsembler   File: test_mau_models.py    License: MIT License 6 votes vote down vote up
def test_save_metrics(self):
        date_for = date(2019, 10, 29)
        course_id = str(self.course_overview.id)
        data = dict(mau=42)
        obj, created = CourseMauMetrics.save_metrics(site=self.site,
                                                     course_id=course_id,
                                                     date_for=date_for,
                                                     data=data)
        assert obj and created

        obj2, created = CourseMauMetrics.save_metrics(site=self.site,
                                                      course_id=course_id,
                                                      date_for=date_for,
                                                      data=data)
        assert obj2 and not created
        assert obj2 == obj

        data['mau'] = 104
        obj3, created = CourseMauMetrics.save_metrics(site=self.site,
                                                      course_id=course_id,
                                                      date_for=date_for,
                                                      data=data,
                                                      overwrite=True)
        assert obj3 == obj2
        assert obj3.mau == data['mau'] 
Example 22
Project: figures   Author: appsembler   File: test_mau_models.py    License: MIT License 6 votes vote down vote up
def test_save_metrics(self):
        date_for = date(2019, 10, 29)
        data = dict(mau=42)
        obj, created = SiteMauMetrics.save_metrics(site=self.site,
                                                   date_for=date_for,
                                                   data=data)
        assert obj and created

        obj2, created = SiteMauMetrics.save_metrics(site=self.site,
                                                    date_for=date_for,
                                                    data=data)
        assert obj2 and not created
        assert obj2 == obj

        data['mau'] = 104
        obj3, created = SiteMauMetrics.save_metrics(site=self.site,
                                                    date_for=date_for,
                                                    data=data,
                                                    overwrite=True)
        assert obj3 == obj2
        assert obj3.mau == data['mau'] 
Example 23
Project: figures   Author: appsembler   File: test_mau_models.py    License: MIT License 6 votes vote down vote up
def test_latest_for_site_month(self):
        date_for = date(2019, 10, 29)
        data = dict(mau=42)
        obj = SiteMauMetrics.objects.latest_for_site_month(site=self.site,
                                                           year=date_for.year,
                                                           month=date_for.month)
        assert not obj

        obj2, created = SiteMauMetrics.save_metrics(site=self.site,
                                                    date_for=date_for,
                                                    data=data)

        # This is just basic. We need to test with multiple records with
        # different modified timestamps to make sure we get the latest
        obj3 = SiteMauMetrics.objects.latest_for_site_month(site=self.site,
                                                            year=date_for.year,
                                                            month=date_for.month)
        assert obj3 and obj3 == obj2 
Example 24
Project: figures   Author: appsembler   File: test_learner_course_grade_metrics_model.py    License: MIT License 6 votes vote down vote up
def setup(self, db):
        self.site = Site.objects.first()
        self.date_for = datetime.date(2018, 2, 2)
        self.course_enrollment = CourseEnrollmentFactory()
        self.grade_data = dict(
            points_possible=10.0,
            points_earned=5.0,
            sections_worked=2,
            sections_possible=2
            )
        self.create_rec = self.grade_data.copy()
        self.create_rec.update(dict(
            site=self.site,
            date_for=self.date_for,
            user=self.course_enrollment.user,
            course_id=self.course_enrollment.course_id)) 
Example 25
Project: figures   Author: appsembler   File: test_site_daily_metrics_model.py    License: MIT License 6 votes vote down vote up
def test_latest_previous_record(self):
        site = SiteFactory()

        # Create a set of records with non-continuous dates
        dates = [
            datetime.date(2019, 10, 1),
            datetime.date(2019, 10, 2),
            datetime.date(2019, 10, 5),
            datetime.date(2019, 10, 29),
            datetime.date(2019, 11, 3),
        ]
        for rec_date in dates:
            SiteDailyMetricsFactory(site=site, date_for=rec_date)

        rec = SiteDailyMetrics.latest_previous_record(site=site)
        assert rec.date_for == dates[-1]

        rec2 = SiteDailyMetrics.latest_previous_record(site=site,
                                                       date_for=dates[-1])
        assert rec2.date_for == dates[-2]

        rec3 = SiteDailyMetrics.latest_previous_record(site=site,
                                                       date_for=dates[0])
        assert not rec3 
Example 26
Project: figures   Author: appsembler   File: test_serializers.py    License: MIT License 6 votes vote down vote up
def test_has_fields(self):
        '''Verify the serialized data has the same keys and values as the model

        Django 2.0 has a convenient method, 'Cast' that will simplify converting
        values:
        https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#cast

        This means that we can retrieve the model instance values as a dict
        and do a simple ``assert self.serializer.data == queryset.values(...)``
        '''

        data = self.serializer.data

        # Hack: Check date and datetime values explicitly
        assert data['date_for'] == str(self.metrics.date_for)
        assert dateutil_parse(data['created']) == self.metrics.created
        assert dateutil_parse(data['modified']) == self.metrics.modified
        check_fields = self.expected_results_keys - self.date_fields - set(['site'])
        for field_name in check_fields:
            db_field = getattr(self.metrics, field_name)
            if type(db_field) in (float, Decimal, ):
                assert float(data[field_name]) == pytest.approx(db_field)
            else:
                assert data[field_name] == db_field 
Example 27
Project: figures   Author: appsembler   File: test_serializers.py    License: MIT License 6 votes vote down vote up
def test_has_fields(self):
        '''Verify the serialized data has the same keys and values as the model

        Django 2.0 has a convenient method, 'Cast' that will simplify converting
        values:
        https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#cast

        This means that we can retrieve the model instance values as a dict
        and do a simple ``assert self.serializer.data == queryset.values(...)``
        '''

        data = self.serializer.data

        # Hack: Check date and datetime values explicitly
        assert data['date_for'] == str(self.site_daily_metrics.date_for)
        assert dateutil_parse(data['created']) == self.site_daily_metrics.created
        assert dateutil_parse(data['modified']) == self.site_daily_metrics.modified
        check_fields = self.expected_results_keys - self.date_fields - set(['site'])
        for field_name in check_fields:
            assert data[field_name] == getattr(self.site_daily_metrics,field_name) 
Example 28
Project: figures   Author: appsembler   File: test_serializers.py    License: MIT License 6 votes vote down vote up
def test_serialize(self):
        site = SiteFactory()
        course_overview = CourseOverviewFactory()
        in_data = dict(
            month_for=datetime.date(2019, 10, 29),
            count=42,
            course_id=str(course_overview.id),
            domain=u'wookie.example.com'
        )

        serializer = CourseMauLiveMetricsSerializer(in_data)
        out_data = serializer.data
        assert set(out_data.keys()) == set(in_data.keys())
        assert out_data['count'] == in_data['count']
        assert dateutil_parse(out_data['month_for']).date() == in_data['month_for']
        assert out_data['domain'] == in_data['domain']
        assert out_data['course_id'] == in_data['course_id'] 
Example 29
Project: figures   Author: appsembler   File: test_serializers.py    License: MIT License 6 votes vote down vote up
def test_serialize(self):
        site = SiteFactory()
        in_data = dict(
            month_for=datetime.date(2019, 10, 29),
            count=42,
            domain=site.domain,
        )

        serializer = SiteMauLiveMetricsSerializer(in_data)

        in_data = dict(
            month_for=datetime.date(2019, 10, 29),
            count=42,
            domain=u'wookie.example.com'
        )

        serializer = SiteMauLiveMetricsSerializer(in_data)
        out_data = serializer.data
        assert set(out_data.keys()) == set(in_data.keys())
        assert out_data['count'] == in_data['count']
        assert dateutil_parse(out_data['month_for']).date() == in_data['month_for']
        assert out_data['domain'] == in_data['domain'] 
Example 30
Project: aospy   Author: spencerahill   File: times.py    License: Apache License 2.0 5 votes vote down vote up
def sel_time(da, start_date, end_date):
    """Subset a DataArray or Dataset for a given date range.

    Ensures that data are present for full extent of requested range.
    Appends start and end date of the subset to the DataArray.

    Parameters
    ----------
    da : DataArray or Dataset
        data to subset
    start_date : np.datetime64
        start of date interval
    end_date : np.datetime64
        end of date interval

    Returns
    ----------
    da : DataArray or Dataset
        subsetted data

    Raises
    ------
    AssertionError
        if data for requested range do not exist for part or all of
        requested range
    """
    _assert_has_data_for_time(da, start_date, end_date)
    da[SUBSET_START_DATE_STR] = xr.DataArray(start_date)
    da[SUBSET_END_DATE_STR] = xr.DataArray(end_date)
    return da.sel(**{TIME_STR: slice(start_date, end_date)})