def test_parse_date(self): """Test :func:`humanfriendly.parse_date()`.""" self.assertEqual((2013, 6, 17, 0, 0, 0), humanfriendly.parse_date('2013-06-17')) self.assertEqual((2013, 6, 17, 2, 47, 42), humanfriendly.parse_date('2013-06-17 02:47:42')) self.assertRaises(humanfriendly.InvalidDate, humanfriendly.parse_date, '2013-06-XY')
def test_parse_date(self): self.assertEqual((2013, 6, 17, 0, 0, 0), humanfriendly.parse_date('2013-06-17')) self.assertEqual((2013, 6, 17, 2, 47, 42), humanfriendly.parse_date('2013-06-17 02:47:42')) try: humanfriendly.parse_date('2013-06-XY') self.assertTrue(False) except Exception, e: self.assertTrue(isinstance(e, humanfriendly.InvalidDate))
def __init__(self, argv): # Authenticate and construct service. self.service, self.arguments = init( argv, 'calendar', 'v3', __doc__, __file__, parents=[self._create_argument_parser()], scope='https://www.googleapis.com/auth/calendar.readonly') # user info self.user = None self.title = None with open("user.json", 'r', encoding='utf-8') as fp: user_data = json.load(fp) self.user = user_data["user"] self.title = user_data["title"] # projects database self.db = CalendarDb(self.arguments.database) self.projects = dict() for p in self.db.get_projects(): self.projects[p.key] = p # start and end date if self.arguments.start_date is None and \ self.arguments.end_date is None and \ self.arguments.period is None: self.arguments.period = "last-month" self.start_date = date.today().replace(day=1) self.end_date = date.today() + timedelta(days=1) if self.arguments.period is not None: if self.arguments.period == "last-month": self.end_date = self.start_date self.start_date = (self.end_date - timedelta(days=1)).replace(day=1) else: raise ValueError("Unknown period: %s" % self.arguments.period) if self.arguments.start_date is not None or \ self.arguments.end_date is not None: raise ValueError( "You cannot combine --period and explicit date") else: if self.arguments.start_date is not None: y, m, d, *r = humanfriendly.parse_date( self.arguments.start_date) self.start_date = date(y, m, d) if self.arguments.end_date is not None: y, m, d, *r = humanfriendly.parse_date(self.arguments.end_date) self.end_date = date(y, m, d)
def parse_date(date): date = date.strip().lower() # TODO: handle day names (e.g. 'monday', 'tuesday', ...) if date == 'today': return datetime.date.today() elif date == 'tomorrow': return datetime.date.today() + datetime.timedelta(days=1) else: return datetime.date(*humanfriendly.parse_date(date)[:3])
def _make_comment(torrent: Torrent, row: lxml.html.HtmlElement) -> Comment: return Comment( website_title=torrent.name, website_link=(torrent.website_link + row.xpath('.//a[contains(@href, "#com-")]/@href')[0]), comment_date=(datetime(*humanfriendly.parse_date( row.xpath('.//div[contains(@class, "comment-details")]' "//small/text()")[0])).replace(tzinfo=timezone.utc)), author_name=row.xpath('.//a[contains(@href, "/user/")]/text()')[0], author_avatar_url=row.xpath('.//img[@class="avatar"]/@src')[0], text=row.xpath(".//div[@markdown-text]/text()")[0], )
def _make_torrent(row: lxml.html.HtmlElement) -> Torrent: torrent_id = int(row.xpath(".//td[3]/a/@id")[0]) return Torrent( torrent_id=torrent_id, name=row.xpath(".//td[3]//span/@title")[0], website_link=f"https://anidex.info/torrent/{torrent_id}", torrent_link=f"https://anidex.info/dl/{torrent_id}", magnet_link=row.xpath('.//a[contains(@href, "magnet")]/@href')[0], size=humanfriendly.parse_size(row.xpath(".//td[7]/text()")[0]), upload_date=datetime( *humanfriendly.parse_date(row.xpath(".//td[8]/@title")[0])), seeder_count=int(row.xpath(".//td[9]/text()")[0]), leecher_count=int(row.xpath(".//td[10]/text()")[0]), download_count=int(row.xpath(".//td[11]/text()")[0]), like_count=int((row.xpath("./td[4]/span/text()") + ["+0"])[0][1:]), comment_count=0, visible=len(row.xpath('.//span[@title="Hidden"]')) == 0, )
def is_after(directory): """ Test based on date input returns true if now is greater than expiry expiry can be callable or a string. The resulting string is parsed by humanfriendly.parse_date """ try: expiry = directory.spec['expiry'] if callable(expiry): expiry = expiry() expiry = datetime(*humanfriendly.parse_date(expiry)) except KeyError: raise UnregulatableError('must specify "expiry" in spec') except humanfriendly.InvalidDate: raise UnregulatableError('expiry must be in format: YYYY-MM-DD [HH:MM:SS]') now = datetime.now() logger.debug('It is currently %s', str(now)) logger.debug('Expiry is %s', str(expiry)) return now > expiry
def _make_torrent(row: lxml.html.HtmlElement) -> Torrent: torrent_id = int( row.xpath(".//td[2]/a[last()]/@href")[0].replace("/view/", "")) return Torrent( torrent_id=torrent_id, name=row.xpath('.//td[2]/a[not(@class="comments")]/@title')[0], website_link=f"https://nyaa.si/view/{torrent_id}", torrent_link=f"https://nyaa.si/download/{torrent_id}.torrent", magnet_link=row.xpath('.//a[contains(@href, "magnet")]/@href')[0], size=humanfriendly.parse_size(row.xpath(".//td[4]/text()")[0]), upload_date=datetime(*humanfriendly.parse_date( row.xpath(".//td[5]/text()")[0])).replace(tzinfo=timezone.utc), seeder_count=int(row.xpath(".//td[6]/text()")[0]), leecher_count=int(row.xpath(".//td[7]/text()")[0]), download_count=int(row.xpath(".//td[8]/text()")[0]), comment_count=int( row.xpath('normalize-space(.//a[@class="comments"])') or "0"), visible=row.xpath("./@class")[0] != "warning", )
def filter(self, name, value, source): sourcevalue = None if name == "type" or name.startswith("type-"): try: sourcevalue = source.entity.type except AttributeError: return False elif name == "age" or name.startswith("age-"): if not source.created: return False now = int(time.time()) value = now - value name = { "age": "created", "age-min": "created-max", "age-max": "created-min", }[name] elif name == "since": if not source.created: return False dt = humanfriendly.parse_date(value) ts = datetime.datetime(*dt).timestamp() value = ts name = "created-min" basename, fn = eval_filter_name(name) if sourcevalue is None: sourcevalue = getattr(source, basename) value = convert_type(value, sourcevalue) return fn(value, sourcevalue)
def filter(self, name, value, source): sourcevalue = None if name == 'type' or name.startswith('type-'): try: sourcevalue = source.entity.type except AttributeError: return False elif name == 'age' or name.startswith('age-'): if not source.created: return False now = int(time.time()) value = now - value name = { 'age': 'created', 'age-min': 'created-max', 'age-max': 'created-min' }[name] elif name == 'since': if not source.created: return False dt = humanfriendly.parse_date(value) ts = datetime.datetime(*dt).timestamp() value = ts name = 'created-min' basename, fn = eval_filter_name(name) if sourcevalue is None: sourcevalue = getattr(source, basename) value = convert_type(value, sourcevalue) return fn(value, sourcevalue)
def test_parse_date(self): """Test :func:`humanfriendly.parse_date()`.""" self.assertEqual((2013, 6, 17, 0, 0, 0), humanfriendly.parse_date('2013-06-17')) self.assertEqual((2013, 6, 17, 2, 47, 42), humanfriendly.parse_date('2013-06-17 02:47:42')) self.assertEqual((2016, 11, 30, 0, 47, 17), humanfriendly.parse_date(u'2016-11-30 00:47:17')) self.assertRaises(humanfriendly.InvalidDate, humanfriendly.parse_date, '2013-06-XY')
def test_parse_date(self): self.assertEqual((2013, 6, 17, 0, 0, 0), humanfriendly.parse_date('2013-06-17')) self.assertEqual((2013, 6, 17, 2, 47, 42), humanfriendly.parse_date('2013-06-17 02:47:42')) self.assertRaises(humanfriendly.InvalidDate, humanfriendly.parse_date, '2013-06-XY')