本文整理匯總了Python中dateparser.parse方法的典型用法代碼示例。如果您正苦於以下問題:Python dateparser.parse方法的具體用法?Python dateparser.parse怎麽用?Python dateparser.parse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類dateparser
的用法示例。
在下文中一共展示了dateparser.parse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: date_to_milliseconds
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def date_to_milliseconds(date_str):
"""Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in readable format, i.e. "January 01, 2018", "11 hours ago UTC", "now UTC"
:type date_str: str
"""
# get epoch value in UTC
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
# parse our date string
d = dateparser.parse(date_str)
# if the date is not timezone aware apply UTC timezone
if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:
d = d.replace(tzinfo=pytz.utc)
# return the difference in time
return int((d - epoch).total_seconds() * 1000.0)
示例2: human_timestamp_to_datetime
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def human_timestamp_to_datetime(human_timestamp, to_utc=False):
"""
Converts a human-readable timestamp into a Python ``DateTime`` object
Args:
human_timestamp (str): A timestamp string
to_utc (bool): Convert the timestamp to UTC
Returns:
DateTime: The converted timestamp
"""
human_timestamp = human_timestamp.replace("-0000", "")
human_timestamp = parenthesis_regex.sub("", human_timestamp)
settings = {}
if to_utc:
settings = {"TO_TIMEZONE": "UTC"}
return dateparser.parse(human_timestamp, settings=settings)
示例3: arg_to_timestamp
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def arg_to_timestamp(arg, arg_name: str, required: bool = False):
if arg is None:
if required is True:
raise ValueError(f'Missing "{arg_name}"')
return None
if isinstance(arg, str) and arg.isdigit():
# timestamp that str - we just convert it to int
return int(arg)
if isinstance(arg, str):
# if the arg is string of date format 2019-10-23T00:00:00 or "3 days", etc
date = dateparser.parse(arg, settings={'TIMEZONE': 'UTC'})
if date is None:
# if d is None it means dateparser failed to parse it
raise ValueError(f'Invalid date: {arg_name}')
return int(date.timestamp())
if isinstance(arg, (int, float)):
return arg
示例4: timeframe_to_utc_zulu_range
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def timeframe_to_utc_zulu_range(timeframe_str):
"""
Converts a time-frame to UTC Zulu format that can be used for startTime and endTime in various Google Vault requests.
"""
try:
parsed_str = dateparser.parse(timeframe_str)
end_time = datetime.utcnow().isoformat() + 'Z' # Current time
start_time = parsed_str.isoformat() + 'Z'
return (start_time, end_time)
except Exception as ex:
err_msg = str(ex)
if 'Quota exceeded for quota metric' in err_msg:
err_msg = 'Quota for Google Vault API exceeded'
return_error('Unable to parse date correctly: {}'.format(err_msg))
else:
raise ex
示例5: extract_from_possible_value_text
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def extract_from_possible_value_text(self, possible_value_or_text):
"""
Check if possible_value_or_text is also containing the value in this field type's data type.
If not parse the possible_value_text var for extracting the first suitable value of this type.
This method does not try to pick value hint or anything similar assuming that there is no
source text available but only the value which is possibly in text form.
:param field:
:param possible_value_or_text:
:return:
"""
try:
maybe_value = self.extract_from_possible_value(possible_value_or_text)
except Exception as e:
raise RuntimeError(f'Incorrect value ("{possible_value_or_text}") for field "{self.field.code}" ({self.type_code})') from e
if maybe_value:
return maybe_value
variants = self._extract_variants_from_text(possible_value_or_text)
if variants:
return variants[0]
return None
示例6: date_to_seconds
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def date_to_seconds(date_str):
"""Convert UTC date to seconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in readable format, i.e. "January 01, 2018", "11 hours ago UTC", "now UTC"
:type date_str: str
"""
# get epoch value in UTC
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
# parse our date string
d = dateparser.parse(date_str)
# if the date is not timezone aware apply UTC timezone
if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:
d = d.replace(tzinfo=pytz.utc)
# return the difference in time
return int((d - epoch).total_seconds())
示例7: date_to_milliseconds
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def date_to_milliseconds(date_str):
"""Convert UTC date to milliseconds
If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/
:param date_str: date in readable format, i.e. "January 01, 2018", "11 hours ago UTC", "now UTC"
:type date_str: str
"""
# get epoch value in UTC
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
# parse our date string
d = dateparser.parse(date_str)
# if the date is not timezone aware apply UTC timezone
if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:
d = d.replace(tzinfo=pytz.utc)
# return the difference in time
return int((d - epoch).total_seconds() * 1000.0)
示例8: parse_iso8601_duration
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def parse_iso8601_duration(cls, duration, start=None, end=None):
match = re.match(
r"(?:P(?P<weeks>\d+)W)|(?:P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D))?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?)", # noqa
duration,
)
time_components = {}
if match:
time_components = match.groupdict(0)
for key, value in time_components.items():
time_components[key] = int(value)
duration = relativedelta(**time_components)
if start:
return parse(start.datetime() + duration)
if end:
return parse(end.datetime() - duration)
return None
示例9: from_iso8601
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def from_iso8601(cls, s):
# # Start and end, such as "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
start, end = s.split("/")
try:
start = parse(start)
except pendulum.parsing.exceptions.ParserError:
# start = self._parse_iso8601_duration(start, end=end)
raise NotImplementedError()
try:
end = parse(end)
except (pendulum.parsing.exceptions.ParserError, TypeError):
end = cls.parse_iso8601_duration(end, start=start)
return cls(start=start, end=end)
# # Start and duration, such as "2007-03-01T13:00:00Z/P1Y2M10DT2H30M"
# # Duration and end, such as "P1Y2M10DT2H30M/2008-05-11T15:30:00Z"
示例10: get_user_reply
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def get_user_reply(self, ctx):
"""Pre-parse user input for wizard"""
def check(m):
return m.author == self.author
try:
reply = await self.bot.wait_for('message', timeout=600, check=check)
except asyncio.TimeoutError:
raise StopWizard
if reply and reply.content:
self.wizard_messages.append(reply)
if reply.content.startswith(await get_pre(self.bot, reply)):
await self.wizard_says(ctx, f'You can\'t use bot commands during the Poll Creation Wizard.\n'
f'Stopping the Wizard and then executing the command:\n`{reply.content}`',
footer=False)
raise StopWizard
elif reply.content.lower() == 'stop':
await self.wizard_says(ctx, 'Poll Wizard stopped.', footer=False)
raise StopWizard
else:
return reply.content
else:
raise InvalidInput
示例11: process_spider_output
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
ts = datetime.now()
stored_meta = response.meta.get('stored_meta')
if stored_meta and 'timestamp' in stored_meta:
ts = datetime.fromtimestamp(stored_meta['timestamp'])
for i in result:
if isinstance(i, (dict, Item)):
i['scraped_time'] = ts
i['scraped_time'] = ts.strftime('%d/%m/%Y')
if 'DataAtualizacaoHumanizada' in i:
updated = parse(i['DataAtualizacaoHumanizada'],
languages=['pt'],
settings={'RELATIVE_BASE': ts})
i['updated_time'] = updated.strftime('%d/%m/%Y')
yield i
示例12: parse_datetime
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def parse_datetime(date_time, loader_context):
if isinstance(date_time, datetime):
return date_time
elif isinstance(date_time, str):
try:
return dateutil_parse(
date_time.strip(),
dayfirst=loader_context.get("dayfirst", False),
yearfirst=loader_context.get("yearfirst", True),
ignoretz=loader_context.get("ignoretz", False),
)
except ValueError:
# If dateutil can't parse it, it might be a human-readable date.
return dateparser.parse(date_time)
else:
raise ValueError("date_time must be datetime or a str.")
示例13: handle
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def handle(self, *args, **options):
force = options["force"]
lt = parse(options["keep"])
if lt is not None:
lt = timezone.make_aware(lt)
for _, model in registered_models.items():
qs = model.history.all()
if lt is not None:
qs = model.history.filter(history_date__lt=lt)
action_str = "Deleting" if force else "Would delete"
self.stdout.write(
f'{action_str} {qs.count()} historical records from model "{model.__name__}"'
)
if force:
qs.delete()
示例14: connect_kernel
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def connect_kernel():
# TODO check status busy/idle
run_sync(manager.list_kernels())
kernels = {
kernel_id: dateparser.parse(kernel["last_activity"])
for kernel_id, kernel in manager._kernels.items()
}
kernel_id = url_escape(sorted(kernels, key=kernels.get)[0])
client = GatewayClient.instance()
url = url_path_join(client.ws_url, client.kernels_endpoint, kernel_id, "channels")
ws_req = HTTPRequest(url=url)
return run_sync(websocket_connect(ws_req))
示例15: _parse_datetime
# 需要導入模塊: import dateparser [as 別名]
# 或者: from dateparser import parse [as 別名]
def _parse_datetime(date_time):
if date_time == "":
return datetime.datetime.now()
return dateparser.parse(date_time)