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


Python date.today方法代码示例

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


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

示例1: from_gsx

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def from_gsx(cls, article):
        """
        Create a local Article from a GSX comms article
        """
        from datetime import date
        from servo.lib.utils import unescape
        aid = article.articleID

        if cls.objects.filter(gsx_id=aid):
            raise ValueError('Article %s already exists' % aid)

        a = Article(gsx_id=aid, priority=article.priority)
        a.date_created = article.createdDate
        a.date_published = date.today()
        a.title = unescape(article.articleTitle)
        a.summary = unescape(article.articleSummary)

        return a 
开发者ID:fpsw,项目名称:Servo,代码行数:20,代码来源:note.py

示例2: get_time

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def get_time(time_format):
    """
    get different time formats:
        - full_sec > current time in seconds
        - stamp > current date time in seconds
        - else > current time in HH:MM:SS
    """
    t = datetime.today()

    if time_format == 'full_sec':
        return t.hour * 3600 + t.minute * 60 + t.second \
             + t.microsecond / 1000000
    elif time_format == 'stamp':
        return float(datetime.now().timestamp())
    else:
        return t.strftime('%H:%M:%S')


# ------------------------------------------------------------------------------
# default variables and values
# ------------------------------------------------------------------------------ 
开发者ID:ffplayout,项目名称:ffplayout-engine,代码行数:23,代码来源:utils.py

示例3: test_freezing_time_in_fixture

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def test_freezing_time_in_fixture(testdir):
    testdir.makepyfile("""
        import pytest
        from datetime import date, datetime

        @pytest.fixture
        def today():
            return datetime.now().date()

        @pytest.mark.freeze_time('2017-05-20 15:42')
        def test_sth(today):
            assert today == date(2017, 5, 20)
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
开发者ID:ktosiek,项目名称:pytest-freezegun,代码行数:18,代码来源:test_freezegun.py

示例4: test_class_move_to

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def test_class_move_to(testdir):
    testdir.makepyfile("""
        from datetime import date
        import pytest

        class TestAsClass(object):

            @pytest.mark.freeze_time
            def test_changing_date(self, freezer):
                freezer.move_to('2017-05-20')
                assert date.today() == date(2017, 5, 20)
                freezer.move_to('2017-05-21')
                assert date.today() == date(2017, 5, 21)
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
开发者ID:ktosiek,项目名称:pytest-freezegun,代码行数:19,代码来源:test_freezegun.py

示例5: test_role_access

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def test_role_access(self):
        r = Role.objects.filter(role='SYSA')[0]
        p = r.person
        p.config['privacy_signed'] = True
        p.config['privacy_da_signed'] = True
        p.save()

        client = Client()
        client.login_user(r.person.userid)
        url = reverse('sysadmin:new_role')

        # test data role expires in the future: should allow.
        resp = client.get(url)
        self.assertEqual(resp.status_code, 200)

        # expire the role: should now forbid.
        r.expiry = date.today() - timedelta(days=2)
        r.save()
        resp = client.get(url)
        self.assertEqual(resp.status_code, 403) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:22,代码来源:tests.py

示例6: update_factory_version

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def update_factory_version(self):
        """Update project (Factory, 13.2, ...) version if is necessary."""

        # XXX TODO - This method have `factory` in the name.  Can be
        # missleading.

        project = self.api.project
        curr_version = date.today().strftime('%Y%m%d')

        self.update_version_attribute(project, curr_version)

        ports_prjs = ['PowerPC', 'ARM', 'zSystems' ]
        for ports in ports_prjs:
            project = self.api.project + ':' + ports
            if self.api.item_exists(project):
                self.update_version_attribute(project, curr_version) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:18,代码来源:accept_command.py

示例7: test_grouper_multilevel_freq

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def test_grouper_multilevel_freq(self):

        # GH 7885
        # with level and freq specified in a pd.Grouper
        from datetime import date, timedelta
        d0 = date.today() - timedelta(days=14)
        dates = date_range(d0, date.today())
        date_index = pd.MultiIndex.from_product(
            [dates, dates], names=['foo', 'bar'])
        df = pd.DataFrame(np.random.randint(0, 100, 225), index=date_index)

        # Check string level
        expected = df.reset_index().groupby([pd.Grouper(
            key='foo', freq='W'), pd.Grouper(key='bar', freq='W')]).sum()
        # reset index changes columns dtype to object
        expected.columns = pd.Index([0], dtype='int64')

        result = df.groupby([pd.Grouper(level='foo', freq='W'), pd.Grouper(
            level='bar', freq='W')]).sum()
        assert_frame_equal(result, expected)

        # Check integer level
        result = df.groupby([pd.Grouper(level=0, freq='W'), pd.Grouper(
            level=1, freq='W')]).sum()
        assert_frame_equal(result, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:test_grouping.py

示例8: get_context

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def get_context(self, request, *args, **kwargs):
        context = super().get_context(request)

        upcoming_events = Event.objects.all().filter(
            Q(date__gt=date.today())).order_by('date')

        # Show three archive issues per page
        paginator = Paginator(upcoming_events, 3)

        upcoming_events_page = request.GET.get("page")

        try:
            paginated_events = paginator.page(upcoming_events_page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            paginated_events = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            paginated_events = paginator.page(paginator.num_pages)

        context["events"] = paginated_events

        return context 
开发者ID:WesternFriend,项目名称:WF-website,代码行数:25,代码来源:models.py

示例9: set_user_info

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def set_user_info(height: int, weight: int, sex: Sex, birth_date: date) -> Packet:
    age = int((date.today() - birth_date).days / 365.25)
    packed_birthday = (encode_int(birth_date.year, length=2) + encode_int(birth_date.month, length=1) +
                       encode_int(birth_date.day, length=1))
    tags = Fitness.SetUserInfo.Tags
    return Packet(
        service_id=Fitness.id,
        command_id=Fitness.SetUserInfo.id,
        command=Command(tlvs=[
            TLV(tag=tags.Height, value=encode_int(height, length=1)),
            TLV(tag=tags.Weight, value=encode_int(weight, length=1)),
            TLV(tag=tags.Age, value=encode_int(age, length=1)),
            TLV(tag=tags.BirthDate, value=packed_birthday),
            TLV(tag=tags.Sex, value=encode_int(sex.value, length=1)),
            TLV(tag=tags.WaistMedian, value=encode_int(int(height * 0.42), length=1)),
            TLV(tag=tags.WaistMax, value=encode_int(int(height * 0.83), length=1)),
        ]),
    ) 
开发者ID:zyv,项目名称:huawei-lpv2,代码行数:20,代码来源:fitness.py

示例10: _format_membership_duration

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def _format_membership_duration(response_data):
        membership_start = datetime.strptime(
            response_data['membership']['start_date'],
            '%Y-%m-%d'
        )
        one_year = timedelta(days=365)
        one_month = timedelta(days=30)
        duration = date.today() - membership_start.date()
        years, remaining_duration = divmod(duration, one_year)
        months, _ = divmod(remaining_duration, one_month)
        membership_duration = []
        if years:
            membership_duration.append('{} years'.format(years))
        if months:
            membership_duration.append(' {} months'.format(str(months)))

        return ' '.join(membership_duration) if membership_duration else None 
开发者ID:MycroftAI,项目名称:selene-backend,代码行数:19,代码来源:account.py

示例11: _add_membership

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def _add_membership(self, membership_change, active_membership):
        if active_membership is None:
            payment_account_id = create_stripe_account(
                membership_change['payment_token'],
                self.account.email_address
            )
        else:
            payment_account_id = active_membership.payment_account_id
        stripe_plan = self._get_stripe_plan(
            membership_change['membership_type']
        )
        payment_id = create_stripe_subscription(payment_account_id, stripe_plan)

        new_membership = AccountMembership(
            start_date=date.today(),
            payment_method=STRIPE_PAYMENT,
            payment_account_id=payment_account_id,
            payment_id=payment_id,
            type=membership_change['membership_type']
        )

        self.account_repository.add_membership(self.account.id, new_membership) 
开发者ID:MycroftAI,项目名称:selene-backend,代码行数:24,代码来源:account.py

示例12: validate_response

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def validate_response(context):
    response_data = context.response.json
    account = context.accounts['foo']
    assert_that(
        response_data['emailAddress'],
        equal_to(account.email_address)
    )
    assert_that(
        response_data['membership']['type'],
        equal_to('Monthly Membership')
    )
    assert_that(response_data['membership']['duration'], none())
    assert_that(
        response_data['membership'], has_item('id')
    )

    assert_that(len(response_data['agreements']), equal_to(3))
    agreement = response_data['agreements'][0]
    assert_that(agreement['type'], equal_to(PRIVACY_POLICY))
    assert_that(
        agreement['acceptDate'],
        equal_to(str(date.today().strftime('%B %d, %Y')))
    )
    assert_that(agreement, has_item('id')) 
开发者ID:MycroftAI,项目名称:selene-backend,代码行数:26,代码来源:profile.py

示例13: _add_account

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def _add_account(context, db):
    test_account = Account(
        email_address='foo@mycroft.ai',
        username='foobar',
        membership=AccountMembership(
            type='Monthly Membership',
            start_date=date.today(),
            payment_method='Stripe',
            payment_account_id='foo',
            payment_id='bar'
        ),
        agreements=[
            AccountAgreement(type=PRIVACY_POLICY, accept_date=date.today())
        ]
    )
    acct_repository = AccountRepository(db)
    acct_repository.add(test_account, 'foo')
    context.account = acct_repository.get_account_by_email(
        test_account.email_address
    ) 
开发者ID:MycroftAI,项目名称:selene-backend,代码行数:22,代码来源:environment.py

示例14: get_device_subscription

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def get_device_subscription(context):
    membership = AccountMembership(
        start_date=date.today(),
        type='Monthly Membership',
        payment_method='Stripe',
        payment_account_id='test_monthly',
        payment_id='stripe_id'
    )
    login = context.device_login
    device_id = login['uuid']
    access_token = login['accessToken']
    headers = dict(Authorization='Bearer {token}'.format(token=access_token))
    db = connect_to_db(context.client_config['DB_CONNECTION_CONFIG'])
    AccountRepository(db).add_membership(context.account.id, membership)
    context.subscription_response = context.client.get(
        '/v1/device/{uuid}/subscription'.format(uuid=device_id),
        headers=headers
    ) 
开发者ID:MycroftAI,项目名称:selene-backend,代码行数:20,代码来源:get_device_subscription.py

示例15: announce

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import today [as 别名]
def announce(name):
    present = date.today()
    print("Running " + name + " at " + str(present), file=sys.stderr)

# make sure to run test file from root directory! 
开发者ID:gcallah,项目名称:indras_net,代码行数:7,代码来源:test_basic.py


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