当前位置: 首页>>代码示例>>Python>>正文


Python datetime.date方法代码示例

本文整理汇总了Python中datetime.date方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.date方法的具体用法?Python datetime.date怎么用?Python datetime.date使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime的用法示例。


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

示例1: datetime_or_default

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:spencerahill,项目名称:aospy,代码行数:20,代码来源:times.py

示例2: download_bill

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:24,代码来源:tools.py

示例3: download_fundflow

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:27,代码来源:tools.py

示例4: list_statistics

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:24,代码来源:wifi.py

示例5: get_available_rooms

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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)) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:22,代码来源:views_api.py

示例6: report_unavailable_room

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:24,代码来源:views_api.py

示例7: get_semester_date

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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") 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:22,代码来源:domain.py

示例8: get_value_sql

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:kayak,项目名称:pypika,代码行数:21,代码来源:terms.py

示例9: test_json

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:manatlan,项目名称:wuy,代码行数:26,代码来源:test_json.py

示例10: test_parameter_array_indexed_json_load

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:pywr,项目名称:pywr,代码行数:25,代码来源:test_parameters.py

示例11: test_parameter_df_json_load

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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() 
开发者ID:pywr,项目名称:pywr,代码行数:19,代码来源:test_parameters.py

示例12: test_parameter_df_embed_load

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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() 
开发者ID:pywr,项目名称:pywr,代码行数:22,代码来源:test_parameters.py

示例13: test_current_ordinal_threshold_parameter

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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() 
开发者ID:pywr,项目名称:pywr,代码行数:26,代码来源:test_parameters.py

示例14: test_get_total_site_users_for_time_period

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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) 
开发者ID:appsembler,项目名称:figures,代码行数:19,代码来源:test_metrics.py

示例15: test_create

# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import date [as 别名]
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'] 
开发者ID:appsembler,项目名称:figures,代码行数:19,代码来源:test_site_monthly_metrics_model.py


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