Python django.utils.dateparse 模块,parse_date() 实例源码

我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用django.utils.dateparse.parse_date()

项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def deserialize_instance(model, data):
    ret = model()
    for k, v in data.items():
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
                elif isinstance(f, BinaryField):
                    v = force_bytes(
                        base64.b64decode(
                            force_bytes(v)))
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
项目:Vestivise    作者:Vestivise    | 项目源码 | 文件源码
def create_transactions(quovo, user):
        quovo_user = user.profile.quovo_user
        latest_history = quovo.get_user_history(quovo_user.quovo_id)
        result = []
        for transaction in latest_history.get('history'):
            t = Transaction.objects.update_or_create(
                quovo_user=quovo_user,
                quovo_id=transaction.get('id'),
                date=parse_date(transaction.get('date')),
                fees=transaction.get('fees'),
                value=transaction.get('value'),
                price=transaction.get('price'),
                quantity=transaction.get('quantity'),
                cusip=transaction.get('cusip'),
                expense_category=transaction.get('expense_category'),
                ticker=transaction.get('ticker'),
                ticker_name=transaction.get('ticker_name'),
                tran_category=transaction.get('tran_category'),
                tran_type=transaction.get('tran_type'),
                memo=transaction.get('memo'),
                account_id=transaction.get('account')
            )
            result.append(t)
        return result
项目:money-to-prisoners-send-money    作者:ministryofjustice    | 项目源码 | 文件源码
def get_govuk_capture_time(self, govuk_payment):
        try:
            capture_submit_time = parse_datetime(
                govuk_payment['settlement_summary'].get('capture_submit_time', '')
            )
            captured_date = parse_date(
                govuk_payment['settlement_summary'].get('captured_date', '')
            )
            if captured_date is not None:
                capture_submit_time = (
                    capture_submit_time or timezone.now()
                ).astimezone(timezone.utc)
                if capture_submit_time.date() < captured_date:
                    return datetime.combine(
                        captured_date, time.min
                    ).replace(tzinfo=timezone.utc)
                elif capture_submit_time.date() > captured_date:
                    return datetime.combine(
                        captured_date, time.max
                    ).replace(tzinfo=timezone.utc)
                else:
                    return capture_submit_time
        except (KeyError, TypeError):
            pass
        raise GovUkPaymentStatusException(
            'Capture date not yet available for payment %s' % govuk_payment['reference']
        )
项目:Provo-Housing-Database    作者:marcopete5    | 项目源码 | 文件源码
def deserialize_instance(model, data):
    ret = model()
    for k, v in data.items():
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
                elif isinstance(f, BinaryField):
                    v = force_bytes(
                        base64.b64decode(
                            force_bytes(v)))
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value
项目:django-classifier    作者:django-stars    | 项目源码 | 文件源码
def to_python_date(value):
        date = parse_date(value)
        if value and not date:
            raise ValueError('Can\'t convert "{}" to date'.format(value))

        return date
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None and not isinstance(value, datetime.date):
            value = parse_date(value)
        return value
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def to_internal_value(self, value):
        input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS)

        if isinstance(value, datetime.datetime):
            self.fail('datetime')

        if isinstance(value, datetime.date):
            return value

        for input_format in input_formats:
            if input_format.lower() == ISO_8601:
                try:
                    parsed = parse_date(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = self.datetime_parser(value, input_format)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.date()

        humanized_format = humanize_datetime.date_formats(input_formats)
        self.fail('invalid', format=humanized_format)
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None and not isinstance(value, datetime.date):
            value = parse_date(value)
        return value
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        for fmt in self.input_formats:
            if fmt.lower() == ISO_8601:
                try:
                    parsed = parse_date(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, fmt)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.date()

        msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats)

        raise ValidationError(msg)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value
项目:django-reservations    作者:kojdjak    | 项目源码 | 文件源码
def create_reservation(field_id, res_date, reservation_time, user):
    """
    Create reservation.

    :param field_id: id of field for which to create reservations
    :param res_date: date on which to create reservation. None -> today
    :param reservation_time: time of reservation
    :param user: actual user or None
    :return:
    """
    field = Field.objects.get(id=field_id)
    today = dateparse.parse_date(res_date) if res_date else timezone.now()
    time = timezone.datetime(today.year, today.month, today.day, int(reservation_time), tzinfo=timezone.now().tzinfo)
    return Reservation.objects.create(name="Reservation", field=field, user=user, time=time)
项目:django-reservations    作者:kojdjak    | 项目源码 | 文件源码
def get_reservations(field_id, res_date):
    """
    Get reservation for a date.

    :param field_id: id of field for which to get reservations
    :param res_date: date on which to get reservations. None -> today
    :return:
    """
    field = Field.objects.get(id=field_id)
    today = dateparse.parse_date(res_date)if res_date else timezone.now()
    time = timezone.datetime(today.year, today.month, today.day, 0)
    return Reservation.objects.filter(field=field_id).filter(time__range=[time, time+timedelta(days=1)])
项目:django-reservations    作者:kojdjak    | 项目源码 | 文件源码
def __init__(self, res_date):
        self.res_date = res_date
        self.today = dateparse.parse_date(res_date) if res_date else timezone.now()
        self.res_date_previous = timezone.datetime(self.today.year, self.today.month, self.today.day-1, 0).strftime("%Y-%m-%d")
        self.res_date_next = timezone.datetime(self.today.year, self.today.month, self.today.day+1, 0).strftime("%Y-%m-%d")
项目:Vestivise    作者:Vestivise    | 项目源码 | 文件源码
def update_transactions(self):
        history = self.get_user_history()
        last_id = None
        if history:
            last_id = history.last().quovo_id
        latest_history = Quovo.get_user_history(self.quovo_id, start_id=last_id)
        for transaction in latest_history.get('history'):
            try:
                Transaction.objects.update_or_create(
                    quovo_user=self,
                    quovo_id=transaction.get('id'),
                    date=parse_date(transaction.get('date')),
                    fees=transaction.get('fees'),
                    value=transaction.get('value'),
                    price=transaction.get('price'),
                    quantity=transaction.get('quantity'),
                    cusip=transaction.get('cusip'),
                    expense_category=transaction.get('expense_category'),
                    ticker=transaction.get('ticker'),
                    ticker_name=transaction.get('ticker_name'),
                    tran_category=transaction.get('tran_category'),
                    tran_type=transaction.get('tran_type'),
                    memo=transaction.get('memo'),
                    account_id=transaction.get('account')
                )
                cusip_exist = Holding.objects.filter(cusip=transaction.get('cusip')).exists()
                ticker_exist = Holding.objects.filter(ticker=transaction.get('ticker')).exists()
                secname_exist = Holding.objects.filter(secname=transaction.get('ticker_name')).exists()
                if not cusip_exist and not ticker_exist and not secname_exist:
                    mailchimp.alert_identify_holdings(transaction.get('ticker_name'))
                    Holding.objects.create(secname=transaction.get('ticker_name'))
            except Exception as e:
                raise Vestivise.NightlyProcessException(e.message)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value
项目:money-to-prisoners-send-money    作者:ministryofjustice    | 项目源码 | 文件源码
def unserialise_date(date_text):
    date_text = force_text(date_text)
    date = parse_date(date_text)
    if not date:
        raise ValueError('Invalid date')
    return date
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.date):
                value = parse_date(value)
        return value
项目:drf-url-filters    作者:manjitkumar    | 项目源码 | 文件源码
def DatetimeWithTZ(msg=None):
    '''
    Checks whether a value is :
        - a valid castable datetime object with timezone.
    '''
    def fn(value):
        try:
            date = parse_datetime(value) or parse_date(value)
            if date is not None:
                return date
            else:
                raise ValueError
        except ValueError:
            raise Invalid('<{0}> is not a valid datetime.'.format(value))
    return fn
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def convert_datefield_value(self, value, expression, connection, context):
        if value is not None and not isinstance(value, datetime.date):
            value = parse_date(value)
        return value
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            if settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return parsed
        except ValueError:
            raise exceptions.ValidationError(
                self.error_messages['invalid_date'],
                code='invalid_date',
                params={'value': value},
            )

        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )
项目:stregsystemet    作者:f-klubben    | 项目源码 | 文件源码
def razzia_view(request):
    default_start = timezone.now().today() - datetime.timedelta(days=-180)
    default_end = timezone.now().today()
    start = request.GET.get('start', default_start.isoformat())
    end = request.GET.get('end', default_end.isoformat())
    products = request.GET.get('products', "")
    username = request.GET.get('username', "")
    title = request.GET.get('razzia_title', "Razzia!")

    try:
        product_list = [int(p) for p in products.split(",")]
    except ValueError:
        return render(request, 'admin/stregsystem/razzia/error_wizarderror.html', {})

    product_dict = {k.name: 0 for k in Product.objects.filter(id__in=product_list)}
    if len(product_list) != len(product_dict.items()):
        return render(request, 'admin/stregsystem/razzia/error_wizarderror.html', {})

    try:
        user = Member.objects.get(username__iexact=username)
    except (Member.DoesNotExist, Member.MultipleObjectsReturned):
        return render(request, 'admin/stregsystem/razzia/wizard_view.html',
                      {
                          'start': start,
                          'end': end,
                          'products': products,
                          'username': username,
                          'razzia_title': title}
                      )

    start_date = dateparse.parse_date(start)
    end_date = dateparse.parse_date(end)
    sales_to_user = _sales_to_user_in_period(username, start_date, end_date, product_list, product_dict)

    return render(request, 'admin/stregsystem/razzia/wizard_view.html',
                  {
                      'razzia_title': title,
                      'username': username,
                      'start': start,
                      'end': end,
                      'products': products,
                      'member_name': user.firstname + " " + user.lastname,
                      'items_bought': sales_to_user.items(),
                  })
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            value = datetime.datetime(value.year, value.month, value.day)
            if settings.USE_TZ:
                # For backwards compatibility, interpret naive datetimes in
                # local time. This won't work during DST change, but we can't
                # do much about it, so we let the exceptions percolate up the
                # call stack.
                warnings.warn("DateTimeField %s.%s received a naive datetime "
                              "(%s) while time zone support is active." %
                              (self.model.__name__, self.name, value),
                              RuntimeWarning)
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_aware(value, default_timezone)
            return value

        try:
            parsed = parse_datetime(value)
            if parsed is not None:
                return parsed
        except ValueError:
            raise exceptions.ValidationError(
                self.error_messages['invalid_datetime'],
                code='invalid_datetime',
                params={'value': value},
            )

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return datetime.datetime(parsed.year, parsed.month, parsed.day)
        except ValueError:
            raise exceptions.ValidationError(
                self.error_messages['invalid_date'],
                code='invalid_date',
                params={'value': value},
            )

        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )