本文整理汇总了Python中django.utils.dateparse.parse_date方法的典型用法代码示例。如果您正苦于以下问题:Python dateparse.parse_date方法的具体用法?Python dateparse.parse_date怎么用?Python dateparse.parse_date使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.dateparse
的用法示例。
在下文中一共展示了dateparse.parse_date方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_date_input
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def parse_date_input(value):
"""Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date.
"""
try:
limit = parse_date(value)
except ValueError:
limit = None
if limit is None:
raise ValueError("'{}' is not a valid date.".format(value))
limit = datetime(limit.year, limit.month, limit.day)
if settings.USE_TZ:
limit = make_aware(limit)
return limit
示例2: convert_values
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def convert_values(self, value, field):
"""SQLite returns floats when it should be returning decimals,
and gets dates and datetimes wrong.
For consistency with other backends, coerce when required.
"""
internal_type = field.get_internal_type()
if internal_type == 'DecimalField':
return util.typecast_decimal(field.format_number(value))
elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
return int(value)
elif internal_type == 'DateField':
return parse_date(value)
elif internal_type == 'DateTimeField':
return parse_datetime_with_timezone_support(value)
elif internal_type == 'TimeField':
return parse_time(value)
# No field, or the field isn't known to be a decimal or integer
return value
示例3: to_python
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
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:
msg = self.error_messages['invalid_date'] % value
raise exceptions.ValidationError(msg)
msg = self.error_messages['invalid'] % value
raise exceptions.ValidationError(msg)
示例4: convert_datefield_value
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
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
示例5: to_python
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
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},
)
示例6: DatetimeWithTZ
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
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
示例7: convert_datefield_value
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def convert_datefield_value(self, value, expression, connection):
if value is not None:
if not isinstance(value, datetime.date):
value = parse_date(value)
return value
示例8: populate_release_date
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def populate_release_date(apps, schema_editor):
WatchMovie = apps.get_model('nefarious', 'WatchMovie')
WatchTVEpisode = apps.get_model('nefarious', 'WatchTVEpisode')
WatchTVSeason = apps.get_model('nefarious', 'WatchTVSeason')
NefariousSettings = apps.get_model('nefarious', 'NefariousSettings')
nefarious_settings = NefariousSettings.objects.all().first()
if not nefarious_settings: # skip if no settings exist
return
tmdb_client = get_tmdb_client(nefarious_settings)
logging.info('Adding release dates')
for media in WatchMovie.objects.all():
try:
movie_result = tmdb_client.Movies(media.tmdb_movie_id)
data = movie_result.info()
release_date = parse_date(data.get('release_date', ''))
update_release_date(media, release_date)
except Exception as e:
logging.exception(e)
for media in WatchTVSeason.objects.all():
try:
season_result = tmdb_client.TV_Seasons(media.watch_tv_show.tmdb_show_id, media.season_number)
data = season_result.info()
release_date = parse_date(data.get('air_date', ''))
update_release_date(media, release_date)
except Exception as e:
logging.exception(e)
for media in WatchTVEpisode.objects.all():
try:
episode_result = tmdb_client.TV_Episodes(media.watch_tv_show.tmdb_show_id, media.season_number, media.episode_number)
data = episode_result.info()
release_date = parse_date(data.get('air_date', ''))
update_release_date(media, release_date)
except Exception as e:
logging.exception(e)
示例9: _is_match
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def _is_match(self, parser):
release_year = dateparse.parse_date(self.tmdb_media['release_date']).strftime('%Y')
return parser.is_match(
title=self.tmdb_media[self._get_tmdb_title_key()],
year=release_year,
)
示例10: field_date_to_json
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def field_date_to_json(self, day):
"""Convert a date to a date triple."""
if isinstance(day, six.string_types):
day = parse_date(day)
return [day.year, day.month, day.day] if day else None
示例11: test_get_revisions_index
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def test_get_revisions_index(self):
response = self.client.get(
reverse('wagtailadmin_pages:revisions_index', args=(self.christmas_event.id, ))
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, formats.localize(parse_date('2013-12-25')))
last_christmas_preview_url = reverse(
'wagtailadmin_pages:revisions_view',
args=(self.christmas_event.id, self.last_christmas_revision.id)
)
last_christmas_revert_url = reverse(
'wagtailadmin_pages:revisions_revert',
args=(self.christmas_event.id, self.last_christmas_revision.id)
)
self.assertContains(response, last_christmas_preview_url)
self.assertContains(response, last_christmas_revert_url)
self.assertContains(response, formats.localize(local_datetime(2014, 12, 25)))
this_christmas_preview_url = reverse(
'wagtailadmin_pages:revisions_view',
args=(self.christmas_event.id, self.this_christmas_revision.id)
)
this_christmas_revert_url = reverse(
'wagtailadmin_pages:revisions_revert',
args=(self.christmas_event.id, self.this_christmas_revision.id)
)
self.assertContains(response, this_christmas_preview_url)
self.assertContains(response, this_christmas_revert_url)
示例12: test_scheduled_revision
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def test_scheduled_revision(self):
self.last_christmas_revision.publish()
self.this_christmas_revision.approved_go_live_at = local_datetime(2014, 12, 26)
self.this_christmas_revision.save()
this_christmas_unschedule_url = reverse(
'wagtailadmin_pages:revisions_unschedule',
args=(self.christmas_event.id, self.this_christmas_revision.id)
)
response = self.client.get(
reverse('wagtailadmin_pages:revisions_index', args=(self.christmas_event.id, ))
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Scheduled for')
self.assertContains(response, formats.localize(parse_date('2014-12-26')))
self.assertContains(response, this_christmas_unschedule_url)
示例13: to_python
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def to_python(self, value):
# Serialising to JSON uses DjangoJSONEncoder, which converts date/time objects to strings.
# The reverse does not happen on decoding, because there's no way to know which strings
# should be decoded; we have to convert strings back to dates here instead.
if value is None or isinstance(value, datetime.date):
return value
else:
return parse_date(value)
示例14: convert_datefield_value
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
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
示例15: process_config_date
# 需要导入模块: from django.utils import dateparse [as 别名]
# 或者: from django.utils.dateparse import parse_date [as 别名]
def process_config_date(cls, config, credential, field_name):
date_value = cls.process_mapping(config.get(field_name), credential)
date_result = None
if date_value:
try:
# could be seconds since epoch
date_result = datetime.utcfromtimestamp(int(date_value))
except ValueError:
# Django method to parse a date string. Must be in ISO8601 format
try:
date_result = parse_datetime(date_value)
if not date_result:
date_result = parse_date(date_value)
if not date_result:
raise ValueError()
date_result = datetime.combine(date_result, datetime.min.time())
date_result = timezone.make_aware(date_result)
except re.error:
raise CredentialException(
"Error parsing {}: {}".format(field_name, date_value)
)
except ValueError:
raise CredentialException(
"Credential {} is invalid: {}".format(field_name, date_value)
)
if not date_result.tzinfo:
# interpret as UTC
date_result = date_result.replace(tzinfo=timezone.utc)
else:
# convert to UTC
date_result = date_result.astimezone(timezone.utc)
return date_result