本文整理汇总了Python中isoweek.Week.withdate方法的典型用法代码示例。如果您正苦于以下问题:Python Week.withdate方法的具体用法?Python Week.withdate怎么用?Python Week.withdate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类isoweek.Week
的用法示例。
在下文中一共展示了Week.withdate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
self.__setattr__(k, v)
if kwargs["archive_date"]:
self.archive_week = Week.withdate(kwargs["archive_date"])
self.lead_time = kwargs["archive_date"] - kwargs["create_date"]
else:
self.archive_date = kwargs["last_move_date"]
self.archive_week = Week.withdate(kwargs["last_move_date"])
self.lead_time = kwargs["last_move_date"] - kwargs["create_date"]
示例2: _populate_year
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def _populate_year(self, year):
index = year - self.dob.year
start_week = Week.withdate(date(year, self.dob.month, self.dob.day))
end_week = Week.withdate(date(year + 1, self.dob.month, self.dob.day))
next_week = start_week
weeks = []
while next_week.monday() < end_week.monday():
week_info = WeekInfo(next_week)
weeks.append(week_info)
self._weeks[next_week] = week_info
next_week += 1
self._years[year] = dict(year=year, index=index, weeks=weeks)
示例3: week
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def week(self):
'Returns the start, end-tuple for a week around self.timestamp'
w = Week.withdate(self.timestamp)
start = clean_day(local_timezone.localize(datetime.combine(w.monday(), datetime.min.time())))
end = start + timedelta(days=6, hours=23, minutes=59, seconds=59)
return (start, end)
示例4: handle_noargs
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def handle_noargs(self, **options):
translation.activate('fr')
week_limit = Week.withdate(Week.thisweek().day(settings.VALIDATING_DAY_OF_WEEK) + relativedelta(days=settings.DELAY_BETWEEN_DEFINITON_N_DELIVERY))
deliveries = models.Delivery.objects.filter(date__lte=week_limit, status='P', subscription__enabled=True).order_by('subscription__customer__account__email')
count=0
for delivery in deliveries:
logger_delivery = logging.getLogger('[%d]' % delivery.id)
subscription = delivery.subscription
customer = subscription.customer
logger_delivery.info(delivery.__unicode__())
for content in delivery.content_set.all():
__extent = content.extent
logger_content = logging.getLogger('[%d] [%20s] [%c] [%3s%%]' % (delivery.id, content.product.name[:20], '*' if content.customized else ' ', __extent))
for contentproduct in content.contentproduct_set.all():
logger_content.info('%d x %20s (%4d) %s' % (contentproduct.quantity, contentproduct.product.name[:20], contentproduct.product.id, contentproduct.product.main_price.supplier_product_url))
if options['browse']:
webbrowser.open(contentproduct.product.main_price.supplier_product_url)
count += 1
if count >= options['pages']:
count = 0
try:
input()
except KeyboardInterrupt:
print('Interrupted'); sys.exit()
logger_delivery.info('')
translation.deactivate()
示例5: handle_noargs
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def handle_noargs(self, **options):
translation.activate('fr')
logging.debug('Command in progress')
week_limit = Week.withdate(Week.thisweek().day(settings.VALIDATING_DAY_OF_WEEK) + relativedelta(days=settings.DELAY_BETWEEN_DEFINITON_N_DELIVERY))
# first changed the status of expired deliveries
deliveries_canceled = models.Delivery.objects.filter(date__lt=week_limit, status='w', subscription__enabled=True)
for delivery in deliveries_canceled:
delivery.status = 'e'
delivery.save()
logging.debug('delivery %d expired' % delivery.id)
# secondly, get all the deliveries with a date higher or equal to J+9 and lesser than J+9+7 with a waiting status and a subscription which accepts direct debit.
deliveries = models.Delivery.objects.filter(date__gte=week_limit, date__lt=week_limit+1, status='w', subscription__direct_debit=True, subscription__enabled=True)
for delivery in deliveries:
delivery.status = 'p'
try:
delivery.save()
except ValueError as e:
logging.debug('delivery %d not payed' % delivery.id)
else:
logging.debug('delivery %d payed' % delivery.id)
translation.deactivate()
示例6: validate_period
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [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
示例7: test_constructors
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [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))
示例8: save
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [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
示例9: get_deliveries_from_subscription
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [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
示例10: get_yw
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def get_yw(str_date, date_format='%Y-%m-%d'):
"""
get week number within a year, from week 0 to week 52
:param str_date:
:param date_format:
:return:
"""
date_str = change_format(str_date, in_format=date_format, out_format='%Y-%m-%d')
date_obj = datetime.strptime(date_str, '%Y-%m-%d')
w = Week.withdate(date(date_obj.year, date_obj.month, date_obj.day))
return str(w[0]) + '-' + str(w[1] if w[1] > 9 else '0' + str(w[1])) # yyyy-ww
示例11: weekly_incidents
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def weekly_incidents(inc):
"""
:param team:
:return:
"""
open_week = Week.withdate(dt.datetime.strptime(inc['opened_at'], '%Y-%m-%d %H:%M:%S').date())
if open_week in incs_by_week.keys():
incs_by_week[open_week] += 1
incs_by_week.update({open_week: incs_by_week[open_week]})
else:
incs_by_week[open_week] = 1
示例12: export_to_ical
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def export_to_ical(destination, lessons, start=None, end=None, year=None, weeks=None):
"""
Export the given lessons to ical for the given year and week or start and end date.
The destination must be the path to the ical file to writer.
lessons must be in the same format as returned by AdUnisHSR.
Weeks must be an iterable returning the KW number(int) (eg. 44, 45, 46)
"""
if start is not None and end is not None:
weeks = range(Week.withdate(start).week, Week.withdate(end).week+1)
year = start.year
elif not (weeks is not None and year is not None):
raise TimeTableException('You must either provide a week and a year or start and end date')
cal = Calendar()
cal.add('prodid', '-//timetable2ical//mxm.dk//')
cal.add('version', '2.0')
for week in weeks:
reference = datetime.combine(Week(year, week).monday(), time.min)
# TODO: KWs!
for lesson in lessons:
event = Event()
# print(lesson)
start = reference + timedelta(
days=DAYS_OF_THE_WEEK.index(lesson['day']),
hours=lesson['start_time'].hour,
minutes=lesson['start_time'].minute)
end = start + timedelta(minutes=45)
event.add('summary', "%s (%s)" % (lesson['name'], lesson['teacher']))
event.add('dtstart', start)
event.add('dtend', end)
event.add('categories', lesson['abbrev'])
cal.add_component(event)
with open(destination, 'wb') as f:
f.write(cal.to_ical())
示例13: __init__
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
cw = Week.withdate(Week.thisweek().sunday() + relativedelta(days=9))
start = self.fields['start']
start_choices = [str(w + cw.week - 1) for w in Week.weeks_of_year(cw.year)]
start_date_choices = ['%s (%s %s)' % ((w + cw.week - 1).day(settings.DELIVERY_DAY_OF_WEEK).strftime('%d-%m-%Y'), _('Week'), (w + cw.week - 1).week) for w in Week.weeks_of_year(cw.year)]
start.choices = zip(start_choices, start_date_choices)
start.initial = cw
for field in ['size', 'frequency', 'duration', 'start']:
self.fields[field].widget.attrs['class'] = 'slidebar-select'
for field in ['criterias', 'receive_only_once']:
self.fields[field].widget.attrs['class'] = 'checkbox-select'
for field in ['carrier']:
self.fields[field].widget.attrs['class'] = 'radio-select'
示例14: __call__
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def __call__(self, wizard, own_data, form_data, tmp_dict):
# print('subscription done')
# print(tmp_dict)
user = get_user(wizard)
customer = user.customer
thematic = get_thematic(form_data['cart'])
customized = own_data.get('customized', False)
duration = int(own_data.get('duration'))
bw = Week.fromstring(own_data.get('start'))
ew = Week.withdate( bw.day(1) + relativedelta(months=duration) )
subscription = models.Subscription.objects.create(customer=customer, size=own_data['size'], carrier=own_data['carrier'], receive_only_once=own_data['receive_only_once'], frequency=int(own_data['frequency']), start=bw, end=ew, comment=form_data['comment'].get('comment', ''))
subscription.criterias = own_data['criterias']
if thematic and not customized:
for e in thematic.thematicextent_set.all():
subscription.extent_set.create(product=e.product, extent=e.extent, customized=False)
subscription.create_deliveries()
tmp_dict['subscription'] = subscription
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/
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 True
示例15: handle_noargs
# 需要导入模块: from isoweek import Week [as 别名]
# 或者: from isoweek.Week import withdate [as 别名]
def handle_noargs(self, **options):
translation.activate('fr')
logging.debug('Command in progress')
self.print_interactive_usage()
if options['test']:
logging.info('[TEST MODE enabled]')
logging.info('')
week_limit = Week.withdate(Week.thisweek().day(settings.VALIDATING_DAY_OF_WEEK) + relativedelta(days=settings.DELAY_BETWEEN_DEFINITON_N_DELIVERY))
deliveries = models.Delivery.objects.filter(date__lte=week_limit, status='p', subscription__enabled=True)
logging.info('Number of deliveries to fullfill: %d' % deliveries.count())
for delivery in deliveries:
logger_delivery = logging.getLogger('[delivery %d]' % delivery.id)
logger_delivery.info('')
logger_delivery.info('Process the delivery: %s' % delivery.__unicode__())
logger_delivery.info('')
subscription = delivery.subscription
subscription_weight = subscription.size.weight - subscription.size.weight*settings.PACKAGING_WEIGHT_RATE/100
subscription_price = subscription.price().price
carrier = subscription.carrier
weight_level = carrier.carrierlevel_set.filter(weight__gte=subscription.size.weight)
if weight_level:
logger_delivery.info('weight level:\t\t%s kg (%s €)' % (weight_level[0].weight, weight_level[0].price))
subscription_price -= weight_level[0].price
logger_delivery.info('carrier:\t\t%s' % carrier.name)
logger_delivery.info('subscription weight:\t%s kg' % subscription_weight)
logger_delivery.info('subscription price:\t%s € (%s €)' % (subscription_price, subscription.price().price))
logger_delivery.info('')
for extent in subscription.extent_set.all():
__extent = extent.extent
logger_extent = logging.getLogger('[delivery %d] [%s] [%s%%]' % (delivery.id, extent.product.name, __extent))
logger_extent.debug('meta-product: %s, extent: %s' % (extent.product.name, __extent))
if extent.customized:
logger_extent = logging.getLogger('[delivery %d] [%s] [%s%%] [custom]' % (delivery.id, extent.product.name, __extent))
logger_extent.info('start fullfilling the delivery cart with a custom content')
logger_extent.info('create custom content object')
content = delivery.content_set.create(product=extent.product, extent=extent.extent, customized=extent.customized) if not options['test'] else None
extent_content = extent.extentcontent_set.get()
for ecp in extent_content.extentcontentproduct_set.all():
logger_extent.info('+ %d x %30s\t\t(%d,\t%s€,\t%sg)' % (ecp.quantity, ecp.product.name[:30], ecp.product.id, ecp.product.price().__unicode__(), ecp.product.weight))
if not options['test']:
content.contentproduct_set.create(product=ecp.product, quantity=ecp.quantity)
continue
def get_product_products(product):
__products = []
for child in product.products_children.all():
__products += get_product_products(child)
__products += product.product_product.filter(status='p').all()
return __products
products = get_product_products(extent.product)
nbr_items = len(products)
prices = [p.main_price.get_after_tax_price_with_fee() if carrier.apply_suppliers_fee else p.main_price.get_after_tax_price() for p in products]
weights = [int(p.weight or settings.DEFAULT_WEIGHT) for p in products]
criterias = []
if subscription.criterias.all():
for p in products:
__filter = p.criterias
for c in subscription.criterias.filter(enabled=True).all():
__filter = __filter.filter(id=c.id)
criterias.append(len(__filter.all()))
else:
criterias = [0] * nbr_items
total_price = round(subscription_price*__extent/100, 2)
total_weight = round(subscription_weight*__extent/100*1000, 2)
total_criteria = round(sum(criterias), 2)
creator.create("Fitness", base.Fitness, weights=(-1.0,-1.0,-1.0,-1.0,))
creator.create("Individual", list, fitness=creator.Fitness)
toolbox = base.Toolbox()
if options['zero']:
toolbox.register("quantity_item", lambda: options['min_quantity'])
else:
toolbox.register("quantity_item", random.randint, options['min_quantity'], options['max_quantity'])
toolbox.register("individual", tools.initRepeat, creator.Individual,
toolbox.quantity_item, nbr_items)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
#.........这里部分代码省略.........