本文整理汇总了Python中isoweek.Week.fromstring方法的典型用法代码示例。如果您正苦于以下问题:Python Week.fromstring方法的具体用法?Python Week.fromstring怎么用?Python Week.fromstring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类isoweek.Week
的用法示例。
在下文中一共展示了Week.fromstring方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_deliveries
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def create_deliveries(self):
s, e = Week.fromstring(str(self.start)), Week.fromstring(str(self.end))
if self.receive_only_once:
d = self.delivery_set.create(date=s)
else:
for i in range(0, e+1-s, self.frequency):
d = self.delivery_set.create(date=s+i)
示例2: test_constructors
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def test_constructors(self):
w = Week(2011,1)
self.assertTrue(w)
self.assertEqual(str(w), "2011W01")
w = Week(2011,0)
self.assertEqual(str(w), "2010W52")
w = Week(2011,-1)
self.assertEqual(str(w), "2010W51")
w = Week(2011,52)
self.assertEqual(str(w), "2011W52")
w = Week(2011,53)
self.assertEqual(str(w), "2012W01")
w = Week(2011,54)
self.assertEqual(str(w), "2012W02")
w = Week(2009,51)
self.assertEqual(str(w), "2009W51")
w = Week(2009,52)
self.assertEqual(str(w), "2009W52")
w = Week(2009,53)
self.assertEqual(str(w), "2010W01")
w = Week(2009,54)
self.assertEqual(str(w), "2010W02")
w = Week.thisweek()
self.assertTrue(w)
w = Week.fromordinal(1)
self.assertEqual(str(w), "0001W01")
w = Week.fromordinal(2)
self.assertEqual(str(w), "0001W02")
w = Week.fromordinal(521723)
self.assertEqual(str(w), "9999W52")
w = Week.fromstring("2011W01")
self.assertEqual(str(w), "2011W01")
w = Week.fromstring("2011-W01")
self.assertEqual(str(w), "2011W01")
from datetime import date
w = Week.withdate(date(2011, 5, 17))
self.assertEqual(str(w), "2011W20")
self.assertEqual(Week.last_week_of_year(2009), Week(2009, 52))
self.assertEqual(Week.last_week_of_year(2010), Week(2010, 52))
self.assertEqual(Week.last_week_of_year(2011), Week(2011, 52))
self.assertEqual(Week.last_week_of_year(9999), Week(9999, 52))
self.assertRaises(ValueError, lambda: Week(0, 0))
self.assertRaises(ValueError, lambda: Week.fromstring("0000W00"))
self.assertRaises(ValueError, lambda: Week.fromstring("foo"))
self.assertRaises(ValueError, lambda: Week.fromordinal(-1))
self.assertRaises(ValueError, lambda: Week.fromordinal(0))
self.assertRaises(ValueError, lambda: Week.fromordinal(521724))
self.assertRaises(ValueError, lambda: Week.last_week_of_year(0))
self.assertRaises(ValueError, lambda: Week.last_week_of_year(10000))
示例3: duration2
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def duration2(self):
if not self.start or not self.end: return None
s, e = Week.fromstring(self.start).day(1), Week.fromstring(self.end).day(1)
r = relativedelta(e,s)
ret = ''
if r.years: ret += _('%d years, ') % r.years
if r.months: ret += _('%d months, ') % r.months
if r.days: ret += _('%d days') % r.days
return ret
示例4: __call__
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def __call__(self, wizard, form, step, data, files):
cart_data = wizard.get_cleaned_data_for_step('cart') or {}
form.thematic = get_thematic(cart_data)
if form.thematic:
for k, f in [('size', form.thematic.size),
('carrier', form.thematic.carrier),
('frequency', form.thematic.frequency),
('start', form.thematic.start_duration)]:
if f: form.fields[k].initial = f
if form.thematic.end_duration:
delta = relativedelta(Week.fromstring(form.thematic.end_duration).day(1),
Week.fromstring(form.thematic.start_duration).day(1))
form.fields['duration'].initial = delta.months
if form.thematic.criterias:
__key = 'thematic_criterias_%d' % form.thematic.id
form.fields['criterias'].initial = cache.get(__key) or [v.id for v in form.thematic.criterias.all()]
if not cache.get(__key): cache.set(__key, form.fields['criterias'].initial)
form.fields['receive_only_once'].initial = form.thematic.receive_only_once
form.fields['customized'].initial = False
for field, locked in [('size', form.thematic.locked_size),
('carrier', form.thematic.locked_carrier),
('receive_only_once', form.thematic.locked_receive_only_once),
('frequency', form.thematic.locked_frequency),
('start', form.thematic.locked_start),
('duration', form.thematic.locked_duration),
('criterias', form.thematic.locked_criterias),
('customized', form.thematic.locked_products)]:
if locked:
attrs = form.fields[field].widget.attrs
attrs['class'] = attrs.get('class', '') + ' disabled'
else:
form.fields['customized'].initial = True
attrs = form.fields['customized'].widget.attrs
attrs['class'] = attrs.get('class', '') + ' disabled'
form.carriers = cache.get('create_carriers') or models.Carrier.objects.select_related().all()
if not cache.get('create_carriers'): cache.set('create_carriers', form.carriers)
form.sizes = cache.get('create_sizes') or models.Size.objects.select_related().order_by('order').all()
if not cache.get('create_sizes'): cache.set('create_sizes', form.sizes)
return form
示例5: validate_period
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def validate_period(period, first_date):
'''
make sure only period is between first_date and today
'''
today = datetime.now().strftime('%Y%m%d')
# Day yyyyMMdd
if type_of_period(period) == 'day':
if period >= first_date and period <= today:
return True
# Week yyyy-Www
elif type_of_period(period) == 'week':
this_week = Week.thisweek()
period_week = Week.fromstring(period)
first_date_week = Week.withdate(datetime.strptime(first_date, '%Y%m%d'))
if period_week >= first_date_week and period_week <= this_week:
return True
# Month yyyyMM
elif type_of_period(period) == 'month':
this_month = datetime.now().strftime('%Y%m')
period_month = period[0:6]
first_date_month = first_date[0:6]
if period_month >= first_date_month and period_month <= this_month:
return True
return False
示例6: save
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def save(self, commit=True):
subscription = super().save(commit=False)
bw = Week.fromstring(self.cleaned_data['start'])
ew = Week.withdate( bw.day(1) + relativedelta(months=int(self.cleaned_data['duration'])) )
subscription.end = ew
if commit:
subscription.save()
subscription.create_deliveries()
return subscription
示例7: get_deliveries_from_subscription
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def get_deliveries_from_subscription(subscription_data):
receive_only_once = subscription_data.get('receive_only_once')
bw = Week.fromstring(str(subscription_data.get('start')))
ew = Week.withdate( bw.day(1) + relativedelta(months=int(subscription_data.get('duration'))) )
nb = len(range(0, ew+1-bw, int(subscription_data.get('frequency'))))
init_price = subscription_data.get('size').default_price().price
prices = get_deliveries(nb, init_price)
if receive_only_once: prices = np.array([prices[0]])
deliveries = [(i+1, '%s (%s %s)' % ((bw+i*2).day(settings.DELIVERY_DAY_OF_WEEK).strftime('%d-%m-%Y'), _('Week'), (bw+i*2).week), p) for i,p in enumerate(prices)]
return deliveries, prices
示例8: period_to_dates
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def period_to_dates(period):
'''
return a list of dates from period
'''
dates = []
today = datetime.now().strftime('%Y%m%d')
if type_of_period(period) == 'day':
if period <= today:
dates.append(period)
# Week yyyy-Www
elif type_of_period(period) == 'week':
week = Week.fromstring(period)
alldates = []
monday = str(week.monday()).replace('-', '')
tuesday = str(week.tuesday()).replace('-', '')
wednesday = str(week.wednesday()).replace('-', '')
thursday = str(week.thursday()).replace('-', '')
friday = str(week.friday()).replace('-', '')
saturday = str(week.saturday()).replace('-', '')
sunday = str(week.sunday()).replace('-', '')
alldates.append(monday, tuesday, wednesday, thursday, friday, saturday, sunday)
for dt in alldates:
if dt <= today:
dates.append(dt)
# Month yyyyMM
elif type_of_period(period) == 'month':
year = int(period[0:4])
month = int(period[4:6])
lastday = calendar.monthrange(year, month)[1]
for day in range(1, lastday+1):
dt = date(year, month, day)
dt_yyyymmdd = dt.strftime('%Y%m%d')
if dt_yyyymmdd <= today:
dates.append(dt_yyyymmdd)
return dates
示例9: nweeks
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def nweeks(self, obj):
if not obj.start or not obj.end: return None
return Week.fromstring(obj.end) - Week.fromstring(obj.start)
示例10: duration
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def duration(self, obj):
if not obj.start or not obj.end: return None
s, e = Week.fromstring(obj.start).day(1), Week.fromstring(obj.end).day(1)
return str(relativedelta(e,s))
示例11: page_urls
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def page_urls(period):
'''
return the next period.
e.g. next period of 20140824 is 20140825
next period of 201408 is 201409
next period of 2014-W34 is 2014-W35
'''
page = dict()
# 'Day', 'Week', 'Month' link to the current day/week/month
today = datetime.now().strftime('%Y%m%d')
this_week = Week.thisweek().isoformat()[:4] + '-' + Week.thisweek().isoformat()[4:]
this_month = datetime.now().strftime('%Y%m')
page['day_url'] = url_for('views.leaderboard_period', period=today)
page['week_url'] = url_for('views.leaderboard_period', period=this_week)
page['month_url'] = url_for('views.leaderboard_period', period=this_month)
if type_of_period(period) == 'day':
# title
today = datetime.strptime(period, '%Y%m%d')
page['title'] = custom_strftime(today, '%a, %B {S} %Y')
# 'prev' and 'next' links
t = time.strptime(period, '%Y%m%d')
today = date(t.tm_year, t.tm_mon, t.tm_mday)
nextday = today + timedelta(1)
prevday = today + timedelta(-1)
page['next_url'] = url_for('views.leaderboard_period', period=nextday.strftime('%Y%m%d'))
page['prev_url'] = url_for('views.leaderboard_period', period=prevday.strftime('%Y%m%d'))
return page
elif type_of_period(period) == 'week':
# title
page['title'] = datetime.strptime(period + '1', '%Y-W%W%w').strftime('Week %W, %Y')
# 'prev' and 'next' links
# begin_of_next_week = time.strptime('201435 1', '%Y%W %w')
# use isoweek instead strptime('%W') since isoweek starts from week 1
# while strptime('%W') returns week number starting from week 0
thisweek = Week.fromstring(period)
nextweek = thisweek + 1
# ISO 8610 format is "YYYYWww" while Moves API takes "YYYY-Www"
page['next_url'] = url_for('views.leaderboard_period', period=nextweek.isoformat()[:4] + '-' + nextweek.isoformat()[4:])
# next_text = 'Week ' + str(nextweek.week) + ', ' + str(nextweek.year)
prevweek = thisweek -1
page['prev_url'] = url_for('views.leaderboard_period', period=prevweek.isoformat()[:4] + '-' + prevweek.isoformat()[4:])
# prev_text = 'Week ' + str(prevweek.week) + ', ' + str(prevweek.year)
elif type_of_period(period) == 'month':
#title
page['title'] = datetime.strptime(period, '%Y%m').strftime('%B %Y')
# 'prev' and 'next' links
t = time.strptime(period,'%Y%m')
thismonth = date(t.tm_year, t.tm_mon, 1)
nextmonth = add_months(thismonth, 1)
prevmonth = add_months(thismonth, -1)
page['next_url'] = url_for('views.leaderboard_period', period=nextmonth.strftime('%Y%m'))
page['prev_url'] = url_for('views.leaderboard_period', period=prevmonth.strftime('%Y%m'))
return page
示例12: done
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def done(self, form_list, **kwargs):
form_data = [form.cleaned_data for form in form_list]
customized = form_data[0].get('customized', False)
try:
thematic = models.Thematic.objects.select_related().get(id=self.kwargs.get('thematic_id', None))
except models.Thematic.DoesNotExist:
thematic = None
thematic_products = [e.product for e in thematic.thematicextent_set.all()] if thematic else []
products = {}
if customized:
for product in pm.Product.objects.select_related().all():
if ('product_%d' % product.id) in form_list[1].data:
products[product] = int(form_list[1].data['product_%d' % product.id])
else:
if thematic:
for e in thematic.thematicextent_set.all():
products[e.product] = e.extent
if not products:
raise forms.forms.ValidationError("no product was selected")
size = form_data[0].get('size')
carrier = form_data[0].get('carrier')
receive_only_once = form_data[0].get('receive_only_once', False)
frequency = int(form_data[0].get('frequency'))
duration = int(form_data[0].get('duration'))
bw = Week.fromstring(form_data[0].get('start'))
ew = Week.withdate( bw.day(1) + relativedelta(months=duration) )
customer = self.request.user.customer
criterias = form_data[0].get('criterias')
subscription = models.Subscription.objects.create(customer=customer, size=size, carrier=carrier, receive_only_once=receive_only_once, frequency=frequency, start=bw, end=ew)
subscription.criterias = criterias
for product, extent in products.items():
subscription.extent_set.create(product=product, extent=extent)
subscription.create_deliveries()
messages.success(self.request, _('The subscription was sucessfuly created.'))
deliveries = subscription.delivery_set.order_by('date')
mm.Message.objects.create_message(participants=[customer], subject=_('Votre abonnement %(subscription_id)d a été crée') % {'subscription_id': subscription.id}, body=_(
"""Bonjour %(name)s,
Nous sommes heureux de vous annoncer que votre abonnement %(subscription_id)d a été crée, il est accessible à l'adresse suivante :
http://www.vegeclic.fr/carts/subscriptions/%(subscription_id)d/deliveries/
Vous êtes invité, à présent, à approvisionner votre portemonnaie vers un solde suffisant afin que l'on valide la première échéance du %(date)s de votre abonnement en cliquant sur le lien suivant :
http://www.vegeclic.fr/wallets/credit/
Si ce n'est pas encore fait, merci de bien vouloir renseigner vos cordonnées à cette adresse :
http://www.vegeclic.fr/customers/addresses/create/
Bien cordialement,
Végéclic.
"""
) % {'name': customer.main_address.__unicode__() if customer.main_address else '', 'date': deliveries[0].get_date_display(), 'subscription_id': subscription.id})
return HttpResponseRedirect('/carts/subscriptions/%d/deliveries/page/1' % subscription.id)
示例13: get_form
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import fromstring [as 别名]
def get_form(self, step=None, data=None, files=None):
form = super().get_form(step, data, files)
# determine the step if not given
if step is None: step = self.steps.current
try:
thematic = models.Thematic.objects.select_related().get(id=self.kwargs.get('thematic_id', None))
except models.Thematic.DoesNotExist:
thematic = None
thematic_products = [e.product for e in thematic.thematicextent_set.all()] if thematic else []
form.thematic_products = thematic_products
if step == '0':
if thematic:
for k, f in [('size', thematic.size),
('carrier', thematic.carrier),
('frequency', thematic.frequency),
('start', thematic.start_duration)]:
if f: form.fields[k].initial = f
if thematic.end_duration:
delta = relativedelta(Week.fromstring(thematic.end_duration).day(1),
Week.fromstring(thematic.start_duration).day(1))
form.fields['duration'].initial = delta.months
for field, locked in [('size', thematic.locked_size),
('carrier', thematic.locked_carrier),
('receive_only_once', thematic.locked_receive_only_once),
('frequency', thematic.locked_frequency),
('start', thematic.locked_start),
('duration', thematic.locked_duration),
('criterias', thematic.locked_criterias)]:
if locked:
form.fields[field].widget.attrs['class'] = form.fields[field].widget.attrs.get('class', '') + ' disabled'
if thematic.criterias:
form.fields['criterias'].initial = [v.id for v in thematic.criterias.all()]
form.products_tree = cache.get('products_tree') or sw.get_products_tree(pm.Product.objects)
if not cache.get('products_tree'): cache.set('products_tree', form.products_tree)
form.carriers = cache.get('create_carriers') or models.Carrier.objects.select_related().all()
if not cache.get('create_carriers'): cache.set('create_carriers', form.carriers)
form.sizes = cache.get('create_sizes') or models.Size.objects.select_related().all()
if not cache.get('create_sizes'): cache.set('create_sizes', form.sizes)
if not thematic: form.fields['customized'].initial = True
elif step == '1':
products = []
for product in pm.Product.objects.order_by('name').all():
if int( self.request.POST.get('product_%d' % product.id, 0) ):
products.append(product)
if not products:
raise forms.forms.ValidationError("no product was selected")
extents = [e.extent for e in thematic.thematicextent_set.all()] if thematic else []
shared_extent = int((100 - sum(extents))/(len(products) - len(extents))) if (len(products) - len(extents)) else 0
form.selected_products = []
for product in products:
extent = None
if product in thematic_products:
extent = thematic.thematicextent_set.get(product=product)
form.selected_products.append((product, extent.extent if extent else shared_extent))
messages.info(self.request, _('In order to lock a product percent, please check the corresponding checkbox.'))
return form