Python datetime.date.today() Examples

The following are 30 code examples of datetime.date.today(). 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 also want to check out all available functions/classes of the module datetime.date , or try the search function .
Example #1
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 7 votes vote down vote up
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
# ------------------------------------------------------------------------------ 
Example #2
Source File: models.py    From WF-website with GNU Affero General Public License v3.0 7 votes vote down vote up
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 
Example #3
Source File: test_freezegun.py    From pytest-freezegun with MIT License 6 votes vote down vote up
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 
Example #4
Source File: tests.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: get_device_subscription.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
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
    ) 
Example #6
Source File: environment.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
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
    ) 
Example #7
Source File: test_grouping.py    From recruit with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: profile.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
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')) 
Example #9
Source File: fitness.py    From huawei-lpv2 with MIT License 6 votes vote down vote up
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)),
        ]),
    ) 
Example #10
Source File: accept_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #11
Source File: accept_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #12
Source File: account.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #13
Source File: test_freezegun.py    From pytest-freezegun with MIT License 6 votes vote down vote up
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 
Example #14
Source File: account.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #15
Source File: note.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #16
Source File: utilities.py    From asciimatics with Apache License 2.0 5 votes vote down vote up
def readable_timestamp(stamp):
    """
    :param stamp: A floating point number representing the POSIX file timestamp.
    :return: A short human-readable string representation of the timestamp.
    """
    if date.fromtimestamp(stamp) == date.today():
        return str(datetime.fromtimestamp(stamp).strftime("%I:%M:%S%p"))
    else:
        return str(date.fromtimestamp(stamp)) 
Example #17
Source File: common.py    From rucio with Apache License 2.0 5 votes vote down vote up
def __dump_url(rse):
    """
    getting potential urls of the dump over last week

    :param rse:          RSE where the dump is released.
    """

    # get the date of the most recent dump
    today = date.today()
    dump_dates = []
    dump_production_day = config_get('bb8', 'dump_production_day', raise_exception=False, default=None)
    if dump_production_day is None:
        for idx in range(0, 7):
            dump_date = today - timedelta(idx)
            dump_dates.append(dump_date.strftime('%d-%m-%Y'))
    else:
        weekdays = {'Sunday': 6, 'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5}
        if dump_production_day not in weekdays:
            print('ERROR: please set the day of a dump creation in bb8 config correctly, e.g. Monday')
            return False
        today_idx = (today.weekday() - weekdays[dump_production_day]) % 7
        dump_date = today - timedelta(today_idx)
        dump_dates = [dump_date.strftime('%d-%m-%Y')]

    # getting structure (template) of url location of a dump
    url_template_str = config_get('bb8', 'dump_url_template', raise_exception=False, default='http://rucio-analytix.cern.ch:8080/LOCKS/GetFileFromHDFS?date=${date}&rse=${rse}')
    url_template = Template(url_template_str)

    # populating url template
    urls = []
    for d in dump_dates:
        url = url_template.substitute({'date': d, 'rse': rse})
        urls.append(url)
    return urls 
Example #18
Source File: sales_team.py    From Odoo_Samples with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_sale_orders_data(self, cr, uid, ids, field_name, arg, context=None):
        obj = self.pool['sale.order']
        month_begin = date.today().replace(day=1)
        date_begin = (month_begin - relativedelta.relativedelta(months=self._period_number - 1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
        date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1]).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)

        res = {}
        for id in ids:
            res[id] = {}
            created_domain = [('section_id', '=', id), ('state', '=', 'draft'), ('date_order', '>=', date_begin), ('date_order', '<=', date_end)]
            validated_domain = [('section_id', '=', id), ('state', 'not in', ['draft', 'sent', 'cancel']), ('date_order', '>=', date_begin), ('date_order', '<=', date_end)]
            res[id]['monthly_quoted'] = json.dumps(self.__get_bar_values(cr, uid, obj, created_domain, ['amount_total', 'date_order'], 'amount_total', 'date_order', context=context))
            res[id]['monthly_confirmed'] = json.dumps(self.__get_bar_values(cr, uid, obj, validated_domain, ['amount_total', 'date_order'], 'amount_total', 'date_order', context=context))

        return res 
Example #19
Source File: msg.py    From SkPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def quote(user, chat, timestamp, content):
        """
        Display a message excerpt as a quote from another user.

        Skype for Web doesn't support native quotes, and instead displays the legacy quote text.  Supported desktop
        clients show a blockquote with the author's name and timestamp underneath.

        .. note:: Anomalous API behaviour: it is possible to fake the message content of a quote.

        Args:
            user (SkypeUser): user who is to be quoted saying the message
            chat (SkypeChat): conversation the quote was originally seen in
            timestamp (datetime.datetime): original arrival time of the quoted message
            content (str): excerpt of the original message to be quoted

        Returns:
            str: tag to display the excerpt as a quote
        """
        # Single conversations lose their prefix here.
        chatId = chat.id if chat.id.split(":")[0] == "19" else SkypeUtils.noPrefix(chat.id)
        # Legacy timestamp includes the date if the quote is not from today.
        unixTime = int(time.mktime(timestamp.timetuple()))
        legacyTime = timestamp.strftime("{0}%H:%M:%S".format("" if timestamp.date() == date.today() else "%d/%m/%Y "))
        return """<quote author="{0}" authorname="{1}" conversation="{2}" timestamp="{3}"><legacyquote>""" \
               """[{4}] {1}: </legacyquote>{5}<legacyquote>\n\n&lt;&lt;&lt; </legacyquote></quote>""" \
               .format(user.id, user.name, chatId, unixTime, legacyTime, content) 
Example #20
Source File: agreement.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_open_dataset():
    return Agreement(
        type=OPEN_DATASET,
        version='Holy Grail',
        effective_date=date.today() - timedelta(days=1)
    ) 
Example #21
Source File: account.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def build_test_membership(**overrides):
    stripe_acct = 'test_stripe_acct_id'
    return AccountMembership(
        type=overrides.get('type') or 'Monthly Membership',
        start_date=overrides.get('start_date') or date.today(),
        payment_method=overrides.get('payment_method') or 'Stripe',
        payment_account_id=overrides.get('payment_account_id') or stripe_acct,
        payment_id=overrides.get('payment_id') or 'test_stripe_payment_id'
    ) 
Example #22
Source File: account.py    From selene-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def build_test_account(**overrides):
    test_agreements = [
        AccountAgreement(type=PRIVACY_POLICY, accept_date=date.today()),
        AccountAgreement(type=TERMS_OF_USE, accept_date=date.today()),
        AccountAgreement(type=OPEN_DATASET, accept_date=date.today())
    ]
    return Account(
        email_address=overrides.get('email_address') or 'foo@mycroft.ai',
        username=overrides.get('username') or 'foobar',
        agreements=overrides.get('agreements') or test_agreements
    ) 
Example #23
Source File: sales_team.py    From Odoo_Samples with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_invoices_data(self, cr, uid, ids, field_name, arg, context=None):
        obj = self.pool['account.invoice.report']
        month_begin = date.today().replace(day=1)
        date_begin = (month_begin - relativedelta.relativedelta(months=self._period_number - 1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
        date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1]).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)

        res = {}
        for id in ids:
            created_domain = [('section_id', '=', id), ('state', 'not in', ['draft', 'cancel']), ('date', '>=', date_begin), ('date', '<=', date_end)]
            res[id] = json.dumps(self.__get_bar_values(cr, uid, obj, created_domain, ['price_total', 'date'], 'price_total', 'date', context=context))
        return res 
Example #24
Source File: test_generate_license.py    From dephell with MIT License 5 votes vote down vote up
def test_generate_license_command(temp_path: Path):
    config = Config()
    config.attach({'project': str(temp_path)})
    command = GenerateLicenseCommand(argv=['MIT'], config=config)
    result = command()

    assert result is True
    assert (temp_path / 'LICENSE').exists()
    content = (temp_path / 'LICENSE').read_text()
    assert 'MIT License' in content
    assert str(date.today().year) in content 
Example #25
Source File: app_svc.py    From caldera with Apache License 2.0 5 votes vote down vote up
def run_scheduler(self):
        while True:
            interval = 60
            for s in await self.get_service('data_svc').locate('schedules'):
                now = datetime.now().time()
                diff = datetime.combine(date.today(), now) - datetime.combine(date.today(), s.schedule)
                if interval > diff.total_seconds() > 0:
                    self.log.debug('Pulling %s off the scheduler' % s.name)
                    sop = copy.deepcopy(s.task)
                    sop.set_start_details()
                    await self._services.get('data_svc').store(sop)
                    self.loop.create_task(sop.run(self.get_services()))
            await asyncio.sleep(interval) 
Example #26
Source File: StatsFetcher.py    From LuckyCAT with GNU General Public License v3.0 5 votes vote down vote up
def fetch_yesterdays_crashes(self, job_name=None):
        date_today = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d')
        if job_name is None:
            url = self.stats_api_url + '/' + date_today
            general_stats = self.get_request(url)
            return general_stats
        else:
            url = self.stats_api_url + '/' + date_today
            general_stats = self.get_request(url)
            return general_stats 
Example #27
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default_loan_duration_can_be_changed(staffapp, settings):
    settings.LOAN_DURATION = 7
    url = reverse('monitoring:loan')
    form = staffapp.get(url).forms['loan_form']
    due_date = (date.today() + timedelta(days=7)).isoformat()
    assert form['due_date'].value == due_date 
Example #28
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        due_date = date.today() + timedelta(days=settings.LOAN_DURATION)
        defaults = {
            'loan_form': LoanForm(initial={'due_date': due_date}),
            'return_form': ReturnForm,
            'loans': Loan.objects.due(),
            'export_form': ExportLoanForm
        }
        defaults.update(kwargs)
        return super().get_context_data(**defaults) 
Example #29
Source File: _downloads.py    From dephell with MIT License 5 votes vote down vote up
def get_downloads_by_category(*, category: str, name: str) -> List[Dict[str, Any]]:
    url = CATEGORIES_URLS[category].format(name)
    with requests_session() as session:
        response = session.get(url)
    response.raise_for_status()
    body = response.json()['data']

    yesterday = date.today() - timedelta(1)
    grouped: DefaultDict[str, DateList]
    grouped = defaultdict(lambda: DateList(start=yesterday - timedelta(30), end=yesterday))
    for line in body:
        category = line['category'].replace('.', '')
        grouped[category].add(date=line['date'], value=line['downloads'])

    result = []
    for category, dates in grouped.items():
        downloads = list(dates)
        if sum(downloads) == 0:
            continue
        result.append(dict(
            category=category,
            day=downloads[-1],
            week=sum(downloads[-7:]),
            month=sum(downloads),
            chart=make_chart(downloads[-28:], group=7),
        ))
    return result 
Example #30
Source File: test_datetime_values.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_setitem_with_string_index(self):
        # GH 23451
        x = pd.Series([1, 2, 3], index=['Date', 'b', 'other'])
        x['Date'] = date.today()
        assert x.Date == date.today()
        assert x['Date'] == date.today()