本文整理匯總了Python中dateutil.parser.parse方法的典型用法代碼示例。如果您正苦於以下問題:Python parser.parse方法的具體用法?Python parser.parse怎麽用?Python parser.parse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類dateutil.parser
的用法示例。
在下文中一共展示了parser.parse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __new__
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def __new__(cls, t, snap=0):
if isinstance(t, (str, bytes)) and t.isdigit():
t = int(t)
if not isinstance(t, (str, bytes)):
from dateutil.tz import tzutc
return datetime.fromtimestamp(t // 1000, tz=tzutc())
try:
units = ["weeks", "days", "hours", "minutes", "seconds"]
diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])}
if len(diffs) == 1:
# Snap > 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance
snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {}
snap_units.pop("day", None)
snap_units.update(microsecond=0)
ts = datetime.now().replace(**snap_units) + relativedelta(**diffs)
cls._precision[ts] = snap_units
return ts
return dateutil_parse(t)
except (ValueError, OverflowError, AssertionError):
raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t))
示例2: test_get_course_enrollments
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def test_get_course_enrollments(self, query_params, filter_args):
expected_data = CourseEnrollment.objects.filter(**filter_args)
request = APIRequestFactory().get(self.request_path + query_params)
force_authenticate(request, user=self.staff_user)
view = self. view_class.as_view({'get': 'list'})
response = view(request)
assert response.status_code == 200
assert set(response.data.keys()) == set(
['count', 'next', 'previous', 'results',])
assert len(response.data['results']) == len(expected_data)
for data in response.data['results']:
db_rec = expected_data.get(id=data['id'])
assert parse(data['created']) == db_rec.created
示例3: as_datetime
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def as_datetime(val):
'''
TODO: Add arg flag to say if caller wants end of day, beginning of day
or a particular time of day if the param is a datetime.date obj
'''
if isinstance(val, datetime.datetime):
return val
elif isinstance(val, datetime.date):
# Return the end of the day, set timezone to be UTC
return datetime.datetime(
year=val.year,
month=val.month,
day=val.day,
).replace(tzinfo=utc)
elif isinstance(val, basestring): # noqa: F821
return dateutil_parse(val).replace(tzinfo=utc)
else:
raise TypeError(
'value of type "{}" cannot be converted to a datetime object'.format(
type(val)))
示例4: as_date
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def as_date(val):
'''Casts the value to a ``datetime.date`` object if possible
Else raises ``TypeError``
'''
# Important to check if datetime first because datetime.date objects
# pass the isinstance(obj, datetime.date) test
if isinstance(val, datetime.datetime):
return val.date()
elif isinstance(val, datetime.date):
return val
elif isinstance(val, basestring): # noqa: F821
return dateutil_parse(val).date()
else:
raise TypeError(
'date cannot be of type "{}".'.format(type(val)) +
' It must be able to be cast to a datetime.date')
示例5: __deserialize_date
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
示例6: __deserialize_datatime
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
示例7: detect_date
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def detect_date(e):
if is_date(e): return True
for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
if isinstance(e, date_type): return True
# Slow!!!
# for date_format in DATE_FORMATS:
# try:
# if datetime.strptime(e, date_format):
# return True
# except:
# continue
# Also slow
# try:
# dparser.parse(e)
# return True
# except: pass
return False
示例8: test_ybd
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def test_ybd(self):
# If we have a 4-digit year, a non-numeric month (abbreviated or not),
# and a day (1 or 2 digits), then there is no ambiguity as to which
# token is a year/month/day. This holds regardless of what order the
# terms are in and for each of the separators below.
seps = ['-', ' ', '/', '.']
year_tokens = ['%Y']
month_tokens = ['%b', '%B']
day_tokens = ['%d']
if PLATFORM_HAS_DASH_D:
day_tokens.append('%-d')
prods = itertools.product(year_tokens, month_tokens, day_tokens)
perms = [y for x in prods for y in itertools.permutations(x)]
unambig_fmts = [sep.join(perm) for sep in seps for perm in perms]
actual = datetime(2003, 9, 25)
for fmt in unambig_fmts:
dstr = actual.strftime(fmt)
res = parse(dstr)
self.assertEqual(res, actual)
示例9: testParseUnicodeWords
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def testParseUnicodeWords(self):
class rus_parserinfo(parserinfo):
MONTHS = [("янв", "Январь"),
("фев", "Февраль"),
("мар", "Март"),
("апр", "Апрель"),
("май", "Май"),
("июн", "Июнь"),
("июл", "Июль"),
("авг", "Август"),
("сен", "Сентябрь"),
("окт", "Октябрь"),
("ноя", "Ноябрь"),
("дек", "Декабрь")]
self.assertEqual(parse('10 Сентябрь 2015 10:20',
parserinfo=rus_parserinfo()),
datetime(2015, 9, 10, 10, 20))
示例10: countdown
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def countdown(self, countdown_target_str: str, stage_name: str, ctx: Context):
countdown_target = parse(countdown_target_str).date()
# Get the current date
today = datetime.date.today()
time_until_target = relativedelta(countdown_target, today)
# Given a number of items, determine whether it should be pluralised.
# Then, return the suffix of 's' if it should be, and '' if it shouldn't.
def suffix_from_number(num):
return "" if num == 1 else "s"
month_or_months = "month" + suffix_from_number(time_until_target.months)
day_or_days = "day" + suffix_from_number(time_until_target.days)
month_countdown = f"{time_until_target.months} {month_or_months}"
day_countdown = f"{time_until_target.days} {day_or_days}"
# Diable the months component of the countdown when there are no months left
if time_until_target.months:
month_and_day_countdown = f"{month_countdown} and {day_countdown}"
else:
month_and_day_countdown = day_countdown
if today > countdown_target:
await ctx.send(f"{stage_name} has begun!")
return
await ctx.send(
f"{stage_name} begins on the {countdown_target_str}.\n"
f"That's in {month_and_day_countdown}!"
)
示例11: string_date_time
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def string_date_time(dstr):
d = parser.parse(dstr).astimezone(tz)
return d.strftime("%Y-%m-%d"), d.strftime("%H:%M:%S")
示例12: setup
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def setup(self, db):
super(TestSiteDailyMetricsView, self).setup(db)
self.first_day = parse('2018-01-01')
self.last_day = parse('2018-03-31')
self.date_fields = set(['date_for', 'created', 'modified',])
self.expected_results_keys = set([o.name for o in SiteDailyMetrics._meta.fields])
field_names = (o.name for o in SiteDailyMetrics._meta.fields
if o.name not in self.date_fields )
self.metrics = generate_sdm_series(self.site, self.first_day, self.last_day)
示例13: test_get_by_date_range
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def test_get_by_date_range(self, first_day, last_day):
'''
Note: This test is sensitive in the order data are compared. It expects
that records are retrieved by date_for, descending.
TODO: Add more date ranges
'''
endpoint = '{}?date_0={}&date_1={}'.format(
self.request_path, first_day, last_day)
expected_data = SiteDailyMetrics.objects.filter(
date_for__range=(first_day, last_day))
factory = APIRequestFactory()
request = factory.get(endpoint)
force_authenticate(request, user=self.staff_user)
view = self.view_class.as_view({'get':'list'})
response = view(request)
assert response.status_code == 200
# Expect the following format for pagination
# {
# "count": 2,
# "next": null, # or a url
# "previous": null, # or a url
# "results": [
# ... # list of the results
# ]
# }
assert set(response.data.keys()) == set(
['count', 'next', 'previous', 'results',])
assert len(response.data['results']) == FiguresLimitOffsetPagination.default_limit
# Hack: Check date and datetime values explicitly
for data in response.data['results']:
db_rec = expected_data.get(id=data['id'])
assert data['date_for'] == str(db_rec.date_for)
assert parse(data['created']) == db_rec.created
assert parse(data['modified']) == db_rec.modified
check_fields = self.expected_results_keys - self.date_fields - set(['site'])
for field_name in check_fields:
assert data[field_name] == getattr(db_rec,field_name)
示例14: setup
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def setup(self, db):
super(TestCourseDailyMetricsView, self).setup(db)
self.first_day = parse('2018-01-01')
self.last_day = parse('2018-03-31')
self.date_fields = set(['date_for', 'created', 'modified',])
self.expected_results_keys = set([o.name for o in CourseDailyMetrics._meta.fields])
field_names = (o.name for o in CourseDailyMetrics._meta.fields
if o.name not in self.date_fields )
self.metrics = generate_cdm_series(self.site, self.first_day, self.last_day)
示例15: assert_response_equal
# 需要導入模塊: from dateutil import parser [as 別名]
# 或者: from dateutil.parser import parse [as 別名]
def assert_response_equal(self, response_data, obj):
'''Convenience method to compare serialized data to model object
'''
# Hack: Check date and datetime values explicitly
assert response_data['date_for'] == str(obj.date_for)
assert parse(response_data['created']) == obj.created
assert parse(response_data['modified']) == obj.modified
check_fields = self.expected_results_keys - self.date_fields - set(['site'])
for field_name in check_fields:
obj_field = getattr(obj, field_name)
if (type(response_data) in (float, Decimal,) or
type(obj_field) in (float, Decimal,)):
assert float(response_data[field_name]) == pytest.approx(obj_field)
else:
assert response_data[field_name] == obj_field