本文整理匯總了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
示例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
# ------------------------------------------------------------------------------
示例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
示例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
示例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)
示例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)
示例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)
示例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
示例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)),
]),
)
示例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
示例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)
示例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'))
示例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
)
示例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
)
示例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!