當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。