本文整理汇总了Python中parsedatetime.Calendar方法的典型用法代码示例。如果您正苦于以下问题:Python parsedatetime.Calendar方法的具体用法?Python parsedatetime.Calendar怎么用?Python parsedatetime.Calendar使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类parsedatetime
的用法示例。
在下文中一共展示了parsedatetime.Calendar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parse_date
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def _parse_date(date_str, tz):
try:
dt = datetime.strptime(date_str.strip(), "%m-%d-%Y %I:%M %p")
return dt.replace(tzinfo=tz).astimezone(UTC)
except ValueError:
# in case like "Yesterday 3:30 PM" or dates like that.
# calculates based on sourceTime. tz is 2p2 forum timezone
source = datetime.now(UTC).astimezone(tz)
dt, pt = parsedatetime.Calendar().parseDT(
date_str, tzinfo=tz, sourceTime=source
)
# parsed as a C{datetime}, means that parsing was successful
if pt == 3:
return dt.astimezone(UTC)
raise ValueError(f"Could not parse date: {date_str}")
示例2: get_timestamp
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def get_timestamp(value):
'''Return timestamp from a human readable date'''
if not value:
return
# If already a timestamp return a float
try:
timestamp = float(value)
return timestamp
except ValueError:
pass
# Convert human readable string to timestamp
cal = pdt.Calendar()
timestamp = (cal.parseDT(value)[0]).timestamp()
return timestamp
示例3: getTimeVec
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def getTimeVec(inStr):
cal = parsedatetime.Calendar()
[T, worked] = cal.parse(fixStr(inStr))
T = [item for item in T]
#if worked == 0:
# print "PARSE FAILED"
#time.struct_time(tm_year=2015, tm_mon=7, tm_mday=3, tm_hour=4, tm_min=6, tm_sec=36, tm_wday=4, tm_yday=184, tm_isdst=-1)
Year = T[0]
Month = T[1]
DayOfMonth = T[2]
Hour24 = T[3]
Minute = T[4]
Second = T[5]
Weekday = T[6]
DayOfYear = T[7]
#NOW = cal.parse("now")
return {"year":Year, "month":Month, "day":DayOfMonth, "hour":Hour24, "minute":Minute, "second":Second, "worked":worked!=0}
示例4: date_time_from_str
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def date_time_from_str(datetime_str):
"""Parse a humanly readable datetime.
Args:
datetime_str: str, humanly readable date time.
Returns:
datetime, correctponding datetime object.
"""
cal = parsedatetime.Calendar()
parsed_result, date_type = cal.parse(datetime_str)
parsed_datetime = None
if date_type == 3:
# parsed_result is a datetime
parsed_datetime = parsed_result
elif date_type in (1, 2):
# parsed_result is struct_time
parsed_datetime = datetime.datetime(*parsed_result[:6])
else:
# Failed to parse
raise ValueError("Could not parse date/time string: " + datetime_str)
return parsed_datetime
示例5: parse_time_string
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def parse_time_string(time_str, tz='US/Pacific'):
""" Convert a date or time string into an arrow object in UTC
:param time_str: the string to convert
:param tz: what timezone to interpret the time_str as *if no tz is specified*
:returns: an arrow object representing the time_str in UTC
:raises ValueError: if the time_str could not be parsed
"""
# parsedatetime doesn't handle ISO-8601 time strings (YYYY-MM-DDThh:mm:ss+zz) so
# try to parse it with arrow first and then use parsedatetime as a fallback (grumble)
t = None
try:
t = arrow.get(time_str)
# If the input string didn't specify a timezone, fill in the default
if len(time_str.split('+')) == 1:
t = t.replace(tzinfo=tz)
except arrow.parser.ParserError:
cal = parsedatetime.Calendar()
parse_result = cal.parse(time_str)
if parse_result[1] == 0:
raise ValueError('Could not understand time {time}'.format(time=time_str))
t = arrow.get(parse_result[0]).replace(tzinfo=tz)
return t.to('utc')
示例6: parse_human_timedelta
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def parse_human_timedelta(human_readable: Optional[str]) -> timedelta:
"""
Returns ``datetime.datetime`` from natural language time deltas
>>> parse_human_datetime('now') <= datetime.now()
True
"""
cal = parsedatetime.Calendar()
dttm = dttm_from_timetuple(datetime.now().timetuple())
date_ = cal.parse(human_readable or "", dttm)[0]
date_ = datetime(
date_.tm_year,
date_.tm_mon,
date_.tm_mday,
date_.tm_hour,
date_.tm_min,
date_.tm_sec,
)
return date_ - dttm
示例7: interval_type
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def interval_type(string):
"""Type parser for argparse. Argument must be a valid interval format.
Supports any format supported by `parsedatetime`, including:
* "30sec" (every 30 seconds)
* "5 minutes" (every 5 minutes)
* "1h" (every hour)
* "2 hours 1 min and 30 seconds"
"""
m = datetime.datetime.min
cal = parsedatetime.Calendar()
interval = cal.parseDT(string, sourceTime=m)[0] - m
if interval == m:
error = "Invalid interval format: {}".format(string)
raise argparse.ArgumentTypeError(error)
return interval
示例8: parseHumanReadableDate
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def parseHumanReadableDate(self,datestr):
"""Parses a human-readable date string to python's date object"""
cal = pdt.Calendar()
now = datetime.datetime.now()
return cal.parseDT(datestr, now)[0].date()
#------------------------ Fitbit to Google Fit convertors ----------------------------
示例9: action
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def action(self):
self._logger.info('Start viewing the log events...')
def _exit(signum, frame):
self._logger.info('Exit by code {} ...'.format(signum))
self._exit = True
signal.signal(signal.SIGTERM, _exit)
signal.signal(signal.SIGINT, _exit)
start = time.time()
if self._start is not None:
time_struct, _ = Calendar().parse(self._start)
start = mktime(time_struct)
start = int(start * 1000)
client = self.get_logs_client()
function = self._config.get_function_name()
event_ids = {}
while self._exit is False:
events = client.get_log_events(function, start, self._filter)
for e in events:
if e['eventId'] not in event_ids:
event_ids[e['eventId']] = None
print(e['message'])
if e['timestamp'] > start:
start = e['timestamp']
event_ids = {}
if not self._follow:
break
time.sleep(self._interval)
示例10: _parse_datetime
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def _parse_datetime(string, timezone):
res, code = parsedatetime.Calendar().parseDT(
string, sourceTime=time.localtime(),
tzinfo=pytz.timezone(timezone),
)
if code == 0:
raise ValueError("Unable to parse %s as a timestamp" % string)
return arrow.Arrow.fromdatetime(res)
示例11: __init__
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def __init__(self, filename):
# load timeline data
s = ''
with open(filename) as f:
s = f.read()
self.data = json.loads(s)
assert 'width' in self.data, 'width property must be set'
assert 'start' in self.data, 'start property must be set'
assert 'end' in self.data, 'end property must be set'
# create drawing
self.width = self.data['width']
self.drawing = svgwrite.Drawing()
self.drawing['width'] = self.width
self.g_axis = self.drawing.g()
# figure out timeline boundaries
self.cal = parsedatetime.Calendar()
self.start_date = self.datetime_from_string(self.data['start'])
self.end_date = self.datetime_from_string(self.data['end'])
delta = self.end_date[0] - self.start_date[0]
padding = datetime.timedelta(seconds=0.1*delta.total_seconds())
self.date0 = self.start_date[0] - padding
self.date1 = self.end_date[0] + padding
self.total_secs = (self.date1 - self.date0).total_seconds()
# set up some params
self.callout_size = (10, 15, 10) # width, height, increment
self.text_fudge = (3, 1.5)
self.tick_format = self.data.get('tick_format', None)
self.markers = {}
# initialize Tk so that font metrics will work
self.tk_root = Tkinter.Tk()
self.fonts = {}
# max_label_height stores the max height of all axis labels
# and is used in the final height computation in build(self)
self.max_label_height = 0
示例12: date_from_string
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def date_from_string(timeString):
cal = pdt.Calendar()
now = datetime.now()
result = str(cal.parseDT(timeString.strip(), now)[0])
return result
示例13: parse_time_interval_seconds
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def parse_time_interval_seconds(time_str):
""" Convert a given time interval (e.g. '5m') into the number of seconds in that interval
:param time_str: the string to parse
:returns: the number of seconds in the interval
:raises ValueError: if the string could not be parsed
"""
cal = parsedatetime.Calendar()
parse_result = cal.parseDT(time_str, sourceTime=datetime.min)
if parse_result[1] == 0:
raise ValueError('Could not understand time {time}'.format(time=time_str))
return (parse_result[0] - datetime.min).total_seconds()
示例14: parse_human_datetime
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def parse_human_datetime(human_readable: str) -> datetime:
"""
Returns ``datetime.datetime`` from human readable strings
>>> from datetime import date, timedelta
>>> from dateutil.relativedelta import relativedelta
>>> parse_human_datetime('2015-04-03')
datetime.datetime(2015, 4, 3, 0, 0)
>>> parse_human_datetime('2/3/1969')
datetime.datetime(1969, 2, 3, 0, 0)
>>> parse_human_datetime('now') <= datetime.now()
True
>>> parse_human_datetime('yesterday') <= datetime.now()
True
>>> date.today() - timedelta(1) == parse_human_datetime('yesterday').date()
True
>>> year_ago_1 = parse_human_datetime('one year ago').date()
>>> year_ago_2 = (datetime.now() - relativedelta(years=1) ).date()
>>> year_ago_1 == year_ago_2
True
"""
try:
dttm = parse(human_readable)
except Exception: # pylint: disable=broad-except
try:
cal = parsedatetime.Calendar()
parsed_dttm, parsed_flags = cal.parseDT(human_readable)
# when time is not extracted, we 'reset to midnight'
if parsed_flags & 2 == 0:
parsed_dttm = parsed_dttm.replace(hour=0, minute=0, second=0)
dttm = dttm_from_timetuple(parsed_dttm.utctimetuple())
except Exception as ex:
logger.exception(ex)
raise ValueError("Couldn't parse date string [{}]".format(human_readable))
return dttm
示例15: extractSeriesReleases
# 需要导入模块: import parsedatetime [as 别名]
# 或者: from parsedatetime import Calendar [as 别名]
def extractSeriesReleases(self, seriesPageUrl, soup):
chapter_divs = soup.find_all("a", class_='chapter-link')
retval = []
for linka in chapter_divs:
state = linka['data-preprocessor-state']
vol = linka['data-preprocessor-vol']
chp = linka['data-preprocessor-chp']
name = linka['data-preprocessor-name']
index = linka['data-preprocessor-index']
title = linka['data-preprocessor-title']
reldate = linka['data-preprocessor-reldate']
href = linka['href']
itemDate, status = parsedatetime.Calendar().parse(reldate)
if status < 1:
continue
reldate = time.mktime(itemDate)
relurl = common.util.urlFuncs.rebaseUrl(linka['href'] + "/", seriesPageUrl)
print([vol, chp, state, linka])
raw_item = {}
raw_item['srcname'] = "Qidian"
raw_item['published'] = float(reldate)
raw_item['linkUrl'] = relurl
if state == '0':
raw_msg = msgpackers.buildReleaseMessageWithType(raw_item, title, None, index, None, tl_type='translated', prefixMatch=True)
retval.append(msgpackers.serialize_message(raw_msg))
elif state == "2":
raw_msg = msgpackers.buildReleaseDeleteMessageWithType(raw_item, title, None, index, None, tl_type='translated', prefixMatch=True)
retval.append(msgpackers.serialize_message(raw_msg))
else:
print("Unknown state:", state)
# Do not add series without 3 chapters.
if len(retval) < 3:
self.log.info("Less then three chapters!")
return []
# if not retval:
# self.log.info("Retval empty?!")
# return []
# return []
return retval