def load(self, api, commit=True): self.chargify_id = int(api.id) self.name = api.name self.kind = api.kind self.unit_name = api.unit_name self.price_per_unit_in_cents = api.price_per_unit_in_cents self.pricing_scheme = api.pricing_scheme if api.created_at: self.created_at = new_datetime(api.created_at) if api.updated_at: self.updated_at = new_datetime(api.updated_at) try: pf = ProductFamily.objects.get( chargify_id=api.product_family_id) except: family = self.gateway.ProductFamily().getById(api.product_family_id) pf = ProductFamily() pf.load(family) pf.save() self.product_family = pf if commit: self.save() return self
def _title_range(reel): agg = models.Issue.objects.filter(pages__reel=reel).distinct().aggregate( mn=Min('date_issued'), mx=Max('date_issued')) if agg['mn'] and agg['mx']: mn = datetime_safe.new_datetime(agg['mn']).strftime('%b %d, %Y') mx = datetime_safe.new_datetime(agg['mx']).strftime('%b %d, %Y') return "%s - %s" % (mn, mx) else: return ""
def _title_range(reel): agg = ( models.Issue.objects.filter(pages__reel=reel).distinct().aggregate(mn=Min("date_issued"), mx=Max("date_issued")) ) if agg["mn"] and agg["mx"]: mn = datetime_safe.new_datetime(agg["mn"]).strftime("%b %d, %Y") mx = datetime_safe.new_datetime(agg["mx"]).strftime("%b %d, %Y") return "%s - %s" % (mn, mx) else: return ""
def load(self, api, commit=True): self.chargify_id = int(api.id) self.state = api.state self.balance_in_cents = api.balance_in_cents self.current_period_started_at = new_datetime(api.current_period_started_at) self.current_period_ends_at = new_datetime(api.current_period_ends_at) if api.trial_started_at: self.trial_started_at = new_datetime(api.trial_started_at) else: self.trial_started_at = None if api.trial_ended_at: self.trial_ended_at = new_datetime(api.trial_ended_at) else: self.trial_ended_at = None if api.activated_at: self.activated_at = new_datetime(api.activated_at) else: self.activated_at = None if api.expires_at: self.expires_at = new_datetime(api.expires_at) else: self.expires_at = None if api.next_assessment_at: self.next_billing_at = new_datetime(api.next_assessment_at) elif api.next_billing_at: self.next_billing_at = new_datetime(api.next_billing_at) else: self.next_billing_at = None self.created_at = new_datetime(api.created_at) self.updated_at = new_datetime(api.updated_at) try: c = Customer.objects.get(chargify_id = api.customer.id) except: c = Customer() c.load(api.customer) self.customer = c try: p = Product.objects.get(chargify_id = api.product.id) except: p = Product() p.load(api.product) p.save() self.product = p if self.credit_card: credit_card = self.credit_card else: credit_card = CreditCard() credit_card.load(api.credit_card) if commit: self.save() return self
def get_recurrence_dates(first_date, recurrences): dates = [] d_start = first_date dt_start = new_datetime(d_start) dt_end = new_datetime(d_start + datetime.timedelta(days=const.ONE_YEAR)) occurrences = recurrences.between( dt_start, dt_end, dtstart=dt_start, inc=True ) for occurrence in occurrences: dates.append(occurrence.date()) return dates
def _format_value(self, value): if value is None: return '' elif hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def label(instance): if isinstance(instance, models.Title): return u"%s (%s) %s-%s" % ( instance.display_name, instance.place_of_publication, instance.start_year, instance.end_year, ) elif isinstance(instance, models.Issue): parts = [] dt = datetime_safe.new_datetime(instance.date_issued) parts.append(dt.strftime("%B %d, %Y")) if instance.edition_label: parts.append(u"%s" % instance.edition_label) return u", ".join(parts) elif isinstance(instance, models.Page): parts = [] if instance.section_label: parts.append(instance.section_label) if instance.number: parts.append("Page %s" % instance.number) parts.append("Image %s" % instance.sequence) return u", ".join(parts) else: return u"%s" % instance
def handle_item(self, key, value, attributes=None): field_name = self.field_mapping.get(key, key) if isinstance(value, datetime.datetime): d = datetime_safe.new_datetime(value) value = d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) self.finish_handle_item(field_name=field_name, value=value, attributes=attributes)
def manipulator_validator_unique_for_date(from_field, date_field, opts, lookup_type, self, field_data, all_data): from django.db.models.fields.related import ManyToOneRel date_str = all_data.get(date_field.get_manipulator_field_names('')[0], None) date_val = oldforms.DateField.html2python(date_str) if date_val is None: return # Date was invalid. This will be caught by another validator. lookup_kwargs = {'%s__year' % date_field.name: date_val.year} if isinstance(from_field.rel, ManyToOneRel): lookup_kwargs['%s__pk' % from_field.name] = field_data else: lookup_kwargs['%s__iexact' % from_field.name] = field_data if lookup_type in ('month', 'date'): lookup_kwargs['%s__month' % date_field.name] = date_val.month if lookup_type == 'date': lookup_kwargs['%s__day' % date_field.name] = date_val.day try: old_obj = self.manager.get(**lookup_kwargs) except ObjectDoesNotExist: return else: if hasattr(self, 'original_object') and self.original_object._get_pk_val() == old_obj._get_pk_val(): pass else: format_string = (lookup_type == 'date') and '%B %d, %Y' or '%B %Y' date_val = datetime_safe.new_datetime(date_val) raise validators.ValidationError, "Please enter a different %s. The one you entered is already being used for %s." % \ (from_field.verbose_name, date_val.strftime(format_string))
def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def default(self, o): if isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return self.DateInt(int(time.mktime(d.timetuple()))) else: return super(DatetimeJSONEncoder, self).default(o)
def render(self, name, value, attrs=None): if value is None: value = '' elif hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) value = value.strftime(self.format) return super(DateTimeInput, self).render(name, value, attrs)
def default(self, o): if isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) elif isinstance(o, datetime.date): d = datetime_safe.new_date(o) return d.strftime(self.DATE_FORMAT) elif isinstance(o, datetime.time): return o.strftime(self.TIME_FORMAT) elif isinstance(o, decimal.Decimal): return str(o) elif isinstance(o, Respuesta): return o.__dict__ elif isinstance(o, models.Model): aux = o.__dict__ return aux elif isinstance(o, ModelState): return "x" elif isinstance(o, QuerySet): data = [] for item in o: data.append(item.__dict__) return data else: return super(MyDjangoJSONEncoder, self).default(o)
def default(self, o): # if isinstance(o, GEOSGeometry): # return o.wkt if(hasattr(o, "__iter__")): iterable = iter(o) return list(iterable) elif(hasattr(o, "__add__") and hasattr(o, "__sub__") and hasattr(o, "__mul__")): return float(o) elif isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.isoformat() elif isinstance(o, datetime.date): d = datetime_safe.new_date(o) return d.strftime(self.DATE_FORMAT) elif isinstance(o, datetime.time): return o.strftime(self.TIME_FORMAT) elif isinstance(o, Promise): return force_unicode(o) elif isinstance(o, Pelicula): the_dict = o.__dict__ the_dict['titulo'] = unicode(o) return the_dict elif(hasattr(o, "__class__")): return o.__dict__ else: return str(o)
def _format_value(self, value): if self.is_localized and not self.manual_format: return formats.localize_input(value) elif self.formatter is not None: value = datetime_safe.new_datetime(value) return self.formatter(value, self.format) return value
def default(self, obj): if isinstance(obj, QuerySet): s = PythonSerializer(self.extra) s.serialize(obj) return s.getvalue() elif isinstance(obj, datetime.datetime):s d = datetime_safe.new_datetime(obj) return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
def value_to_string(self, obj): val = self._get_val_from_obj(obj) if val is None: data = '' else: d = datetime_safe.new_datetime(val) data = d.strftime('%Y-%m-%d %H:%M:%S') return data
def _format_value(self, value): # import ipdb; ipdb.set_trace() if self.is_localized: return formats.localize_input(value) elif hasattr(value, "strftime"): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def value_to_string(self, obj): val = self._get_val_from_obj(obj) if val is None: data = '' else: d = datetime_safe.new_datetime(val) data = format(d, self.format) return data
def get_uri(self, action, obj=None, date=None): """ Returns an RFC3987 IRI ID for the given object, action and date. """ if date is None: date = action.timestamp date = datetime_safe.new_datetime(date).strftime('%Y-%m-%d') return 'tag:%s,%s:%s' % (Site.objects.get_current().domain, date, self.get_url(action, obj, False))
def date2str(date, template=None): """ datetime.strftime глючит с годом < 1900 типа обходной маневр (взято из django) WARNING from django: # This library does not support strftime's \"%s\" or \"%y\" format strings. # Allowed if there's an even number of \"%\"s because they are escaped. """ return datetime_safe.new_datetime(date).strftime( template or settings.DATE_FORMAT or '%d.%m.%Y')
def flatten_data(self,follow, obj = None): val = self._get_val_from_obj(obj) date_field, time_field = self.get_manipulator_field_names('') if val is None: date_data = time_data = '' else: d = datetime_safe.new_datetime(val) date_data = d.strftime('%Y-%m-%d') time_data = d.strftime('%H:%M:%S') return {date_field: date_data, time_field: time_data}
def get_string_value(self, obj, field): """ Convert a field's value to a string. """ if isinstance(field, models.DateTimeField): d = datetime_safe.new_datetime(getattr(obj, field.name)) value = d.strftime("%Y-%m-%d %H:%M:%S") else: value = field.flatten_data(follow=None, obj=obj).get(field.name, "") return smart_unicode(value)
def get_tag_uri(url, date): """ Creates a TagURI. See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = "" if date is not None: d = ",%s" % datetime_safe.new_datetime(date).strftime("%Y-%m-%d") return "tag:%s%s:%s/%s" % (bits.hostname, d, bits.path, bits.fragment)
def default(self, o): if isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.strftime("%sT%sZ" % (self.DATE_FORMAT, self.TIME_FORMAT)) elif isinstance(o, datetime.date): d = datetime_safe.new_date(o) return d.strftime(self.DATE_FORMAT) elif isinstance(o, datetime.time): return o.strftime(self.TIME_FORMAT) else: return super(SolrJSONEncoder, self).default(o)
def rfc3339_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) if is_aware(date): time_str = date.strftime('%Y-%m-%dT%H:%M:%S') offset = date.tzinfo.utcoffset(date) timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + "%+03d:%02d" % (hour, minute) else: return date.strftime('%Y-%m-%dT%H:%M:%SZ')
def get_tag_uri(url, date): """ Creates a TagURI. See http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse.urlparse(url) d = '' if date is not None: d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d') return u'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment)
def rfc3339_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) time_str = date.strftime('%Y-%m-%dT%H:%M:%S') offset = date.utcoffset() # Historically, this function assumes that naive datetimes are in UTC. if offset is None: return time_str + 'Z' else: timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d:%02d' % (hour, minute)
def rfc2822_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) # We do this ourselves to be timezone aware, email.Utils is not tz aware. if date.tzinfo: time_str = date.strftime('%a, %d %b %Y %H:%M:%S ') offset = date.tzinfo.utcoffset(date) timezone = (offset.days * 24 * 60) + (offset.seconds / 60) hour, minute = divmod(timezone, 60) return time_str + "%+03d%02d" % (hour, minute) else: return date.strftime('%a, %d %b %Y %H:%M:%S -0000')
def load_api(self): """ Load data into chargify api object """ subscription = self.gateway.Subscription() if self.chargify_id: subscription.id = str(self.chargify_id) #subscription.product = self.product.api subscription.product_handle = self.product_handle subscription.balance_in_cents = self.balance_in_cents if self.next_assessment_at: subscription.next_assessment_at = new_datetime(self.next_assessment_at) if self.next_billing_at: #not passed back from chargify under this node, check for set subscription.next_billing_at = new_datetime(self.next_billing_at) if self.customer.chargify_id is None: subscription.customer = self.customer._api(nodename='customer_attributes') else: #subscription.customer = self.customer.api subscription.customer_reference = self.customer_reference subscription.credit_card = self.credit_card.api #if self.credit_card: # subscription.credit_card = self.credit_card._api('credit_card_attributes') return subscription
def rfc2822_date(date): # We can't use strftime() because it produces locale-dependent results, so # we have to map english month and day names manually months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',) days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) # We do this ourselves to be timezone aware, email.Utils is not tz aware. dow = days[date.weekday()] month = months[date.month - 1] time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) offset = date.utcoffset() # Historically, this function assumes that naive datetimes are in UTC. if offset is None: return time_str + '-0000' else: timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d%02d' % (hour, minute)
def localize_input(value, default=None): """ Checks if an input value is a localizable type and returns it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = force_str(default or get_format('DATE_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.time): format = force_str(default or get_format('TIME_INPUT_FORMATS')[0]) return value.strftime(format) return value
def rfc2822_date(date): # We can't use strftime() because it produces locale-dependent results, so # we have to map english month and day names manually months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',) days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) # We do this ourselves to be timezone aware, email.Utils is not tz aware. dow = days[date.weekday()] month = months[date.month - 1] time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') if is_aware(date): offset = date.tzinfo.utcoffset(date) timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d%02d' % (hour, minute) else: return time_str + '-0000'
def default(self, o): def _call_or_access(x): """Call if callable, otherwise just access.""" return x() if hasattr(x, '__call__') else x if hasattr(o, 'as_dict'): # TODO as_dict circular reference checking fail d = _call_or_access(o.as_dict) if isinstance(d, dict): return d else: raise TypeError("as_dict method did not return a dict") elif hasattr(o, 'as_list'): # TODO as_list circular reference checking fail l = _call_or_access(o.as_list) if isinstance(l, list): return l else: raise TypeError("as_list method did not return a list") elif isinstance(o, QuerySet): # treat as list return list(o) elif isinstance(o, Model): return self._model_as_dict(o) elif isinstance(o, Promise): # see http://code.djangoproject.com/ticket/5868 return force_unicode(o) elif isinstance(o, Decimal): # json.dumps() cant handle Decimal return str(o) elif isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT)) elif isinstance(o, datetime.date): d = datetime_safe.new_date(o) return d.strftime(self.DATE_FORMAT) elif isinstance(o, datetime.time): return o.strftime(self.TIME_FORMAT) else: return super(ExtendedJSONEncoder, self).default(o)
def localize_input(value, default=None): """ <<<<<<< HEAD Checks if an input value is a localizable type and returns it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, six.string_types): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return six.text_type(value) elif isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = force_str(default or get_format('DATE_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.time): format = force_str(default or get_format('TIME_INPUT_FORMATS')[0])
def label(instance): if isinstance(instance, models.Title): return u'%s (%s) %s-%s' % (instance.display_name, instance.place_of_publication, instance.start_year, instance.end_year) elif isinstance(instance, models.Issue): parts = [] dt = datetime_safe.new_datetime(instance.date_issued) parts.append(dt.strftime('%B %d, %Y')) if instance.edition_label: parts.append(u"%s" % instance.edition_label) return u', '.join(parts) elif isinstance(instance, models.Page): parts = [] if instance.section_label: parts.append(instance.section_label) if instance.number: parts.append('Page %s' % instance.number) parts.append('Image %s' % instance.sequence) return u', '.join(parts) else: return u"%s" % instance
def localize_input(value, default=None): """ Check if an input value is a localizable type and return it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return str(value) elif isinstance(value, (decimal.Decimal, float, int)): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = default or get_format("DATETIME_INPUT_FORMATS")[0] return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = default or get_format("DATE_INPUT_FORMATS")[0] return value.strftime(format) elif isinstance(value, datetime.time): format = default or get_format("TIME_INPUT_FORMATS")[0] return value.strftime(format) return value
def rfc3339_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) time_str = date.strftime('%Y-%m-%dT%H:%M:%S')
def load(self, api, commit=True): self.chargify_id = int(api.id) self.state = api.state self.balance_in_cents = api.balance_in_cents self.total_revenue = api.total_revenue_in_cents self.coupon_code = api.coupon_code try: self.current_period_started_at = new_datetime(api.current_period_started_at) self.current_period_ends_at = new_datetime(api.current_period_ends_at) except: # it could be none, if subscription is cancelled pass if api.trial_started_at: self.trial_started_at = new_datetime(api.trial_started_at) else: self.trial_started_at = None if api.trial_ended_at: self.trial_ended_at = new_datetime(api.trial_ended_at) else: self.trial_ended_at = None if api.canceled_at: self.canceled_at = new_datetime(api.canceled_at) else: self.canceled_at = None if api.activated_at: self.activated_at = new_datetime(api.activated_at) else: self.activated_at = None if api.expires_at: self.expires_at = new_datetime(api.expires_at) else: self.expires_at = None self.created_at = new_datetime(api.created_at) self.updated_at = new_datetime(api.updated_at) try: c = Customer.objects.get(chargify_id = api.customer.id) except: log.debug("cant get customer. will create new one! ") c = Customer() c = c.load(api.customer) self.customer = c try: p = Product.objects.get(chargify_id = api.product.id) except: log.debug("cant get product. will create new one! ") p = Product() p.load(api.product) p.save() self.product = p # aganzha ???? # credit_card = CreditCard() # credit_card.load(api.credit_card, commit=commit) # self.credit_card = credit_card if self.credit_card: self.credit_card.load(api.credit_card) # credit_card = self.credit_card else: log.debug("cant get customer. will create new one!") credit_card = CreditCard() credit_card.load(api.credit_card) self.credit_card = credit_card if commit: self.save() return self
def render(self, value, obj=None): if not value: return "" if settings.USE_TZ: value = timezone.localtime(value) return datetime_safe.new_datetime(value).strftime(self.formats[0])
def format_value(self, value): if hasattr(value, 'strftime'): value = datetime_safe.new_datetime(value) return value.strftime(self.format) return value
def default(self, o): if isinstance(o, datetime.datetime): d = datetime_safe.new_datetime(o) return d.strftime('%Y-%m-%dT%H:%M:%SZ') else: return super(SolrJSONEncoder, self).default(o)
def strftime(d, fmt): """works with datetimes with years less than 1900 """ return datetime_safe.new_datetime(d).strftime(fmt)
def load(self, api, commit=True): self.chargify_id = int(api.id) self.state = api.state self.balance_in_cents = api.balance_in_cents self.current_period_started_at = new_datetime( api.current_period_started_at) self.current_period_ends_at = new_datetime(api.current_period_ends_at) if api.trial_started_at: self.trial_started_at = new_datetime(api.trial_started_at) else: self.trial_started_at = None if api.trial_ended_at: self.trial_ended_at = new_datetime(api.trial_ended_at) else: self.trial_ended_at = None if api.activated_at: self.activated_at = new_datetime(api.activated_at) else: self.activated_at = None if api.expires_at: self.expires_at = new_datetime(api.expires_at) else: self.expires_at = None if api.next_assessment_at: self.next_assessment_at = new_datetime(api.next_assessment_at) else: self.next_assessment_at = None if api.created_at: self.created_at = new_datetime(api.created_at) if api.updated_at: self.updated_at = new_datetime(api.updated_at) try: c = Customer.objects.get(chargify_id=api.customer.id) except: c = Customer() c.load(api.customer) self.customer = c try: p = Product.objects.get(chargify_id=api.product.id) except: p = Product() p.load(api.product) p.save() self.product = p if self.credit_card: credit_card = self.credit_card else: credit_card = CreditCard() credit_card.load(api.credit_card) if commit: self.save() for subscomp in api.getComponents(): try: sc = SubscriptionComponent.objects.get( component__chargify_id=subscomp.component_id, subscription__chargify_id=subscomp.subscription_id) except: sc = SubscriptionComponent() sc.load(subscomp) sc.save() return self
def strftime_safe(d, fmt): """Works with datetimes with years less than 1900 for %Y Python 2.7's datetime.strftime does not handle these """ return datetime_safe.new_datetime(d).strftime(fmt)