jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/868829 )
Change subject: [textlib] replace addOnly parameter with add_only to be consistent
......................................................................
[textlib] replace addOnly parameter with add_only to be consistent
- replace addOnly parameter with add_only in replaceLanguageLinks
and replaceCategoryLinks to be consistent with replaceCategoryInPlace
and due to PEP8
- deprecate the old variant
- update documentation
- decrease nested flow statements in replaceCategoryLinks
Change-Id: Ic9ed8b374f9a9b6af19621f824723f7184ed3804
---
M pywikibot/textlib.py
1 file changed, 68 insertions(+), 47 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py
index 8b252a8..c7d1368 100644
--- a/pywikibot/textlib.py
+++ b/pywikibot/textlib.py
@@ -28,6 +28,7 @@
from pywikibot.tools import (
ModuleDeprecationWrapper,
deprecated,
+ deprecated_args,
first_lower,
first_upper,
)
@@ -904,7 +905,7 @@
# Adding the text
text += '\n' + add
# Reputting the categories
- text = replaceCategoryLinks(text, categories_inside, site, addOnly=True)
+ text = replaceCategoryLinks(text, categories_inside, site, add_only=True)
# Adding the interwiki
return replaceLanguageLinks(text, interwiki_inside, site)
@@ -1145,19 +1146,22 @@
return removeLanguageLinks(text, site, marker)
-def replaceLanguageLinks(oldtext: str, new: dict, site=None,
- addOnly: bool = False, template: bool = False,
+@deprecated_args(addOnly='add_only') # since 8.0
+def replaceLanguageLinks(oldtext: str,
+ new: dict,
+ site: Optional['pywikibot.site.BaseSite'] = None,
+ add_only: bool = False,
+ template: bool = False,
template_subpage: bool = False) -> str:
"""Replace inter-language links in the text with a new set of links.
:param oldtext: The text that needs to be modified.
- :param new: A dict with the Site objects as keys, and Page or Link objects
- as values (i.e., just like the dict returned by getLanguageLinks
- function).
+ :param new: A dict with the Site objects as keys, and Page or Link
+ objects as values (i.e., just like the dict returned by
+ :func:`getLanguageLinks` function).
:param site: The site that the text is from.
- :type site: pywikibot.Site
- :param addOnly: If True, do not remove old language links, only add new
- ones.
+ :param add_only: If True, do not remove old language links, only add
+ new ones.
:param template: Indicates if text belongs to a template page or not.
:param template_subpage: Indicates if text belongs to a template sub-page
or not.
@@ -1171,7 +1175,7 @@
cseparator = site.family.category_text_separator
separatorstripped = separator.strip()
cseparatorstripped = cseparator.strip()
- if addOnly:
+ if add_only:
s2 = oldtext
else:
s2 = removeLanguageLinksAndSeparator(oldtext, site=site, marker=marker,
@@ -1203,7 +1207,7 @@
s2 = removeCategoryLinksAndSeparator(
s2.replace(marker, cseparatorstripped).strip(), site) \
+ separator + s
- newtext = replaceCategoryLinks(s2, cats, site=site, addOnly=True)
+ newtext = replaceCategoryLinks(s2, cats, site=site, add_only=True)
# for Wikitravel's language links position.
# (not supported by rewrite - no API)
elif site.family.name == 'wikitravel':
@@ -1480,19 +1484,21 @@
return text
-def replaceCategoryLinks(oldtext: str, new, site=None,
- addOnly: bool = False) -> str:
+@deprecated_args(addOnly='add_only') # since 8.0
+def replaceCategoryLinks(oldtext: str,
+ new: Iterable,
+ site: Optional['pywikibot.site.BaseSite'] = None,
+ add_only: bool = False) -> str:
"""
Replace all existing category links with new category links.
:param oldtext: The text that needs to be replaced.
:param new: Should be a list of Category objects or strings
- which can be either the raw name or [[Category:..]].
- :type new: iterable
+ which can be either the raw name or ``[[Category:..]]``.
:param site: The site that the text is from.
- :type site: pywikibot.Site
- :param addOnly: If addOnly is True, the old category won't be deleted and
- the category(s) given will be added (and they won't replace anything).
+ :param add_only: If add_only is True, the old category won't be
+ deleted and the category(s) given will be added (and they won't
+ replace anything).
:return: The modified text.
"""
# Find a marker that is not already in the text.
@@ -1507,41 +1513,40 @@
iseparator = site.family.interwiki_text_separator
separatorstripped = separator.strip()
iseparatorstripped = iseparator.strip()
- if addOnly:
+ if add_only:
cats_removed_text = oldtext
else:
cats_removed_text = removeCategoryLinksAndSeparator(
oldtext, site=site, marker=marker, separator=separatorstripped)
new_cats = categoryFormat(new, insite=site)
- if new_cats:
- if site.code in site.family.category_attop:
- newtext = new_cats + separator + cats_removed_text
- else:
- # calculate what was after the categories links on the page
- firstafter = cats_removed_text.find(marker)
- if firstafter < 0:
- firstafter = len(cats_removed_text)
- else:
- firstafter += len(marker)
- # Is there text in the 'after' part that means we should keep it
- # after?
- if '</noinclude>' in cats_removed_text[firstafter:]:
- if separatorstripped:
- new_cats = separator + new_cats
- newtext = (cats_removed_text[:firstafter].replace(marker, '')
- + new_cats + cats_removed_text[firstafter:])
- elif site.code in site.family.categories_last:
- newtext = (cats_removed_text.replace(marker, '').strip()
- + separator + new_cats)
- else:
- interwiki = getLanguageLinks(cats_removed_text, insite=site)
- langs_removed_text = removeLanguageLinksAndSeparator(
- cats_removed_text.replace(marker, ''), site, '',
- iseparatorstripped) + separator + new_cats
- newtext = replaceLanguageLinks(
- langs_removed_text, interwiki, site, addOnly=True)
- else:
+ if not new_cats:
newtext = cats_removed_text.replace(marker, '')
+ elif site.code in site.family.category_attop:
+ newtext = new_cats + separator + cats_removed_text
+ else:
+ # calculate what was after the categories links on the page
+ firstafter = cats_removed_text.find(marker)
+ if firstafter < 0:
+ firstafter = len(cats_removed_text)
+ else:
+ firstafter += len(marker)
+ # Is there text in the 'after' part that means we should keep it
+ # after?
+ if '</noinclude>' in cats_removed_text[firstafter:]:
+ if separatorstripped:
+ new_cats = separator + new_cats
+ newtext = (cats_removed_text[:firstafter].replace(marker, '')
+ + new_cats + cats_removed_text[firstafter:])
+ elif site.code in site.family.categories_last:
+ newtext = (cats_removed_text.replace(marker, '').strip()
+ + separator + new_cats)
+ else:
+ interwiki = getLanguageLinks(cats_removed_text, insite=site)
+ langs_removed_text = removeLanguageLinksAndSeparator(
+ cats_removed_text.replace(marker, ''), site, '',
+ iseparatorstripped) + separator + new_cats
+ newtext = replaceLanguageLinks(
+ langs_removed_text, interwiki, site, add_only=True)
# special parts under categories
under_categories = []
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/868829
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ic9ed8b374f9a9b6af19621f824723f7184ed3804
Gerrit-Change-Number: 868829
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/871263 )
Change subject: [bugfix] Add Timestamp.__repr__() method to unify the result
......................................................................
[bugfix] Add Timestamp.__repr__() method to unify the result
Unify representation for Timestamp object
which is different between CPython and Pypy
Bug: T325905
Change-Id: I9b471d120956cb9adac1ecf179bfe0712d5d67e6
---
M pywikibot/time.py
1 file changed, 18 insertions(+), 0 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/time.py b/pywikibot/time.py
index 63bca0d..e96a5f7 100644
--- a/pywikibot/time.py
+++ b/pywikibot/time.py
@@ -293,6 +293,11 @@
"""
return f'{self.posix_timestamp():.6f}'
+ def __repr__(self) -> str:
+ """Unify repr string between CPython and Pypy (T325905)."""
+ s = super().__repr__()
+ return f'{type(self).__name__}{s[s.find("("):]}'
+
def __str__(self) -> str:
"""Return a string format recognized by the API."""
return self.isoformat()
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/871263
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I9b471d120956cb9adac1ecf179bfe0712d5d67e6
Gerrit-Change-Number: 871263
Gerrit-PatchSet: 3
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/871237 )
Change subject: Make some string operations robust and verbose
......................................................................
Make some string operations robust and verbose
Use removeprefix/removesuffix where they correspond
to the intent.
Change-Id: Ia1323e0f02c30ae3b55874cb41029346ef925639
---
M pywikibot/__init__.py
M pywikibot/data/sparql.py
M pywikibot/family.py
M tests/family_tests.py
M scripts/category_redirect.py
M tests/gui_tests.py
M pywikibot/pagegenerators/_factory.py
M pywikibot/scripts/preload_sites.py
M pywikibot/i18n.py
M pywikibot/site_detect.py
M scripts/claimit.py
M pywikibot/data/api/_paraminfo.py
M pywikibot/config.py
M tests/__init__.py
14 files changed, 45 insertions(+), 24 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 9202523..f49d581 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -691,7 +691,7 @@
# also allow entity URIs to be provided via unit parameter
if isinstance(unit, str) \
- and unit.partition('://')[0] not in ('http', 'https'):
+ and not unit.startswith(('http://', 'https://')):
raise ValueError("'unit' must be an ItemPage or entity uri.")
if error is None and not self._require_errors(site):
diff --git a/pywikibot/config.py b/pywikibot/config.py
index 1746a02..66248b3 100644
--- a/pywikibot/config.py
+++ b/pywikibot/config.py
@@ -62,6 +62,7 @@
List,
Mapping,
Tuple,
+ removeprefix,
removesuffix,
)
from pywikibot.logging import error, output, warning
@@ -338,7 +339,7 @@
base_dir = ''
for arg in sys.argv[1:]:
if arg.startswith('-dir:'):
- base_dir = arg[5:]
+ base_dir = removeprefix(arg, '-dir:')
base_dir = os.path.expanduser(base_dir)
break
else:
diff --git a/pywikibot/data/api/_paraminfo.py b/pywikibot/data/api/_paraminfo.py
index 87422f4..f3accae 100644
--- a/pywikibot/data/api/_paraminfo.py
+++ b/pywikibot/data/api/_paraminfo.py
@@ -243,7 +243,8 @@
params['modules'] = [mod for mod in module_batch
if not mod.startswith('query+')
and mod not in self.root_modules]
- params['querymodules'] = [mod[6:] for mod in module_batch
+ params['querymodules'] = [removeprefix(mod, 'query+')
+ for mod in module_batch
if mod.startswith('query+')]
for mod in set(module_batch) & self.root_modules:
diff --git a/pywikibot/data/sparql.py b/pywikibot/data/sparql.py
index 0f0dcc0..1b3fcc4 100644
--- a/pywikibot/data/sparql.py
+++ b/pywikibot/data/sparql.py
@@ -11,7 +11,7 @@
from requests.exceptions import Timeout
from pywikibot import Site, config, sleep, warning
-from pywikibot.backports import Dict, List
+from pywikibot.backports import Dict, List, removeprefix
from pywikibot.comms import http
from pywikibot.exceptions import Error, TimeoutError
@@ -227,9 +227,8 @@
:return: ID of Wikibase object, e.g. Q1234
"""
- urllen = len(self.entity_url)
if self.value.startswith(self.entity_url):
- return self.value[urllen:]
+ return removeprefix(self.value, self.entity_url)
return None
def __repr__(self) -> str:
diff --git a/pywikibot/family.py b/pywikibot/family.py
index dff749a..87519ca 100644
--- a/pywikibot/family.py
+++ b/pywikibot/family.py
@@ -19,7 +19,13 @@
import pywikibot
from pywikibot import config
-from pywikibot.backports import Dict, List, Set, Tuple # skipcq: PY-W2000
+from pywikibot.backports import ( # skipcq: PY-W2000
+ Dict,
+ List,
+ Set,
+ Tuple,
+ removesuffix,
+)
from pywikibot.exceptions import FamilyMaintenanceWarning, UnknownFamilyError
from pywikibot.tools import classproperty, deprecated, remove_last_args
@@ -1035,7 +1041,7 @@
def scriptpath(self, code):
"""Extract the script path from the URL."""
if self.url.path.endswith('/api.php'):
- return self.url.path[0:-8]
+ return removesuffix(self.url.path, '/api.php')
# AutoFamily refers to the variable set below, not the function
# but the reference must be given here
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index 9a19dac..a18fa8a 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -41,6 +41,7 @@
Match,
Sequence,
cache,
+ removesuffix,
)
from pywikibot.plural import plural_rule
@@ -810,7 +811,7 @@
pathname = os.path.join(next(iter(mod.__path__)), package)
# build a list of languages in that directory
- langs = [filename.partition('.')[0]
+ langs = [removesuffix(filename, '.json')
for filename in sorted(os.listdir(pathname))
if filename.endswith('.json')]
diff --git a/pywikibot/pagegenerators/_factory.py b/pywikibot/pagegenerators/_factory.py
index f32c8e3..d965d26 100644
--- a/pywikibot/pagegenerators/_factory.py
+++ b/pywikibot/pagegenerators/_factory.py
@@ -23,6 +23,7 @@
List,
Sequence,
Tuple,
+ removeprefix,
)
from pywikibot.bot import ShowingListOption
from pywikibot.data import api
@@ -622,7 +623,7 @@
value = pywikibot.input('What namespace are you filtering on?')
not_key = 'not:'
if value.startswith(not_key):
- value = value[len(not_key):]
+ value = removeprefix(value, not_key)
resolve = self.site.namespaces.resolve
not_ns = set(resolve(value.split(',')))
if not self._namespaces:
diff --git a/pywikibot/scripts/preload_sites.py b/pywikibot/scripts/preload_sites.py
index 6273279..533f739 100755
--- a/pywikibot/scripts/preload_sites.py
+++ b/pywikibot/scripts/preload_sites.py
@@ -28,7 +28,7 @@
from typing import Optional, Union
import pywikibot
-from pywikibot.backports import List, Set
+from pywikibot.backports import List, Set, removeprefix
from pywikibot.family import Family
@@ -100,6 +100,6 @@
for arg in pywikibot.handle_args():
if arg in families_list:
fam.add(arg)
- elif arg.startswith('-worker'):
- worker = int(arg.partition(':')[2])
+ elif arg.startswith('-worker:'):
+ worker = int(removeprefix(arg, '-worker:'))
preload_families(fam or families_list, worker)
diff --git a/pywikibot/site_detect.py b/pywikibot/site_detect.py
index b4b2f6b..45f269d 100644
--- a/pywikibot/site_detect.py
+++ b/pywikibot/site_detect.py
@@ -16,6 +16,7 @@
import pywikibot
from pywikibot.comms.http import fetch
+from pywikibot.backports import removesuffix
from pywikibot.exceptions import ServerError
from pywikibot.tools import MediaWikiVersion
@@ -45,8 +46,7 @@
:raises Timeout: a timeout occurred while loading the site
:raises RuntimeError: Version not found or version less than 1.27
"""
- if fromurl.endswith('$1'):
- fromurl = fromurl[:-2]
+ fromurl = removesuffix(fromurl, '$1')
r = fetch(fromurl, **kwargs)
check_response(r)
diff --git a/scripts/category_redirect.py b/scripts/category_redirect.py
index fd90c6f..532116a 100755
--- a/scripts/category_redirect.py
+++ b/scripts/category_redirect.py
@@ -42,7 +42,7 @@
import pywikibot
from pywikibot import config, i18n, pagegenerators
-from pywikibot.backports import Tuple
+from pywikibot.backports import Tuple, removeprefix
from pywikibot.bot import ConfigParserBot, SingleSiteBot
from pywikibot.exceptions import CircularRedirectError, Error, NoPageError
@@ -495,8 +495,7 @@
options = {}
for arg in pywikibot.handle_args(args):
if arg.startswith('-delay:'):
- pos = arg.find(':')
- options[arg[1:pos]] = int(arg[pos + 1:])
+ options['delay'] = int(removeprefix(arg, '-delay:'))
else:
# generic handling of we have boolean options
options[arg[1:]] = True
diff --git a/scripts/claimit.py b/scripts/claimit.py
index cfffe99..ac4f9e6 100755
--- a/scripts/claimit.py
+++ b/scripts/claimit.py
@@ -52,6 +52,7 @@
#
import pywikibot
from pywikibot import WikidataBot, pagegenerators
+from pywikibot.backports import removeprefix
from pywikibot.tools.itertools import itergroup
@@ -114,7 +115,7 @@
for arg in local_args:
# Handle args specifying how to handle duplicate claims
if arg.startswith('-exists:'):
- exists_arg = arg.split(':')[1]
+ exists_arg = removeprefix(arg, '-exists:')
continue
# Handle page generator args
if gen.handle_arg(arg):
diff --git a/tests/__init__.py b/tests/__init__.py
index c4b9b3c..a06d063 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -27,7 +27,7 @@
import pywikibot.data.api
from pywikibot import config
-from pywikibot.backports import Dict, List
+from pywikibot.backports import Dict, List, removesuffix
from pywikibot.data.api import CachedRequest
from pywikibot.data.api import Request as _original_Request
from pywikibot.tools import PYTHON_VERSION
@@ -176,7 +176,7 @@
def _unknown_test_modules():
"""List tests which are to be executed."""
dir_list = os.listdir(join_tests_path())
- all_test_set = {name[0:-9] for name in dir_list # strip '_tests.py'
+ all_test_set = {removesuffix(name, '_tests.py') for name in dir_list
if name.endswith('_tests.py')
and not name.startswith('_')} # skip __init__.py and _*
diff --git a/tests/family_tests.py b/tests/family_tests.py
index b8b1f33..a1d649c 100755
--- a/tests/family_tests.py
+++ b/tests/family_tests.py
@@ -36,7 +36,7 @@
self.assertTrue(iter(f.domains))
for domain in f.domains:
self.assertIsInstance(domain, str)
- if domain.split(':', 1)[0] != 'localhost':
+ if not domain.startswith('localhost:'):
self.assertIn('.', domain)
self.assertEqual(f.name, name)
diff --git a/tests/gui_tests.py b/tests/gui_tests.py
index 5439738..a908542 100755
--- a/tests/gui_tests.py
+++ b/tests/gui_tests.py
@@ -22,8 +22,8 @@
def test_tk_dialog(self):
"""Test Tk dialog."""
desc = 'foo'
- image = 'tests/data/images/MP_sounds.png'
- filename = image.rsplit('/', 1)[1]
+ filename = 'MP_sounds.png'
+ image = f'tests/data/images/{filename}'
box = Tkdialog(desc, image, filename)
# skip after ~100 ms
box.root.after(100, box.skip_file)
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/871237
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ia1323e0f02c30ae3b55874cb41029346ef925639
Gerrit-Change-Number: 871237
Gerrit-PatchSet: 3
Gerrit-Owner: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/863328 )
Change subject: [Bugfix] Implement comparison for WbTime object
......................................................................
[Bugfix] Implement comparison for WbTime object
- I used changeset 316220 as a basis for the tests
- For the sake of simplicity, all of the other changes
in the changeset were omitted
- This implementation does not change any current attributes
- This implementation factors in the correct number of days
in a month
- This implementation factors in leap years and the calendar model
when calculating leap years
- Note the difference in behavior of __ge__/__le__ and __eq__/__ne__
Bug: T148280
Change-Id: I694886fd4b264e97c351a8b2a5aefd2b5878be69
---
M pywikibot/__init__.py
M tests/wikibase_tests.py
2 files changed, 127 insertions(+), 1 deletion(-)
Approvals:
Matěj Suchánek: Looks good to me, but someone else must approve
RPI2026F1: Looks good to me, but someone else must approve
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index db7bdfe..9202523 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -319,6 +319,21 @@
_items = ('year', 'month', 'day', 'hour', 'minute', 'second',
'precision', 'before', 'after', 'timezone', 'calendarmodel')
+ _month_offset = {
+ 1: 0,
+ 2: 31, # Jan -> Feb: 31 days
+ 3: 59, # Feb -> Mar: 28 days, plus 31 days in Jan -> Feb
+ 4: 90, # Mar -> Apr: 31 days, plus 59 days in Jan -> Mar
+ 5: 120, # Apr -> May: 30 days, plus 90 days in Jan -> Apr
+ 6: 151, # May -> Jun: 31 days, plus 120 days in Jan -> May
+ 7: 181, # Jun -> Jul: 30 days, plus 151 days in Jan -> Jun
+ 8: 212, # Jul -> Aug: 31 days, plus 181 days in Jan -> Jul
+ 9: 243, # Aug -> Sep: 31 days, plus 212 days in Jan -> Aug
+ 10: 273, # Sep -> Oct: 30 days, plus 243 days in Jan -> Sep
+ 11: 304, # Oct -> Nov: 31 days, plus 273 days in Jan -> Oct
+ 12: 334, # Nov -> Dec: 30 days, plus 304 days in Jan -> Nov
+ }
+
def __init__(self,
year: Optional[int] = None,
month: Optional[int] = None,
@@ -349,6 +364,12 @@
of the event, in the range −180° to 180°, multiplied by 4 to convert
to minutes.
+ Comparison information: When using the greater than or equal to
+ operator, or the less than or equal to operator, two different time
+ objects with the same UTC time after factoring in timezones are
+ considered equal. However, the equality operator will return false
+ if the timezone is different.
+
:param year: The year as a signed integer of between 1 and 16 digits.
:param month: Month of the timestamp, if it exists.
:param day: Day of the timestamp, if it exists.
@@ -406,7 +427,6 @@
.format(Site()))
calendarmodel = site.calendarmodel()
self.calendarmodel = calendarmodel
-
# if precision is given it overwrites the autodetection above
if precision is not None:
if (isinstance(precision, int)
@@ -418,6 +438,61 @@
else:
raise ValueError(f'Invalid precision: "{precision}"')
+ def _getSecondsAdjusted(self) -> int:
+ """Return an internal representation of the time object as seconds.
+
+ The value adjusts itself for timezones. It is not compatible with
+ before/after.
+
+ This value should *only* be used for comparisons, and
+ its value may change without warning.
+
+ :return: An integer roughly representing the number of seconds
+ since January 1, 0000 AD, adjusted for leap years.
+ """
+ # This function ignores leap seconds. Since it is not required
+ # to correlate to an actual UNIX timestamp, this is acceptable.
+
+ # We are always required to have a year.
+ elapsed_seconds = int(self.year * 365.25 * 24 * 60 * 60)
+ if self.month > 1:
+ elapsed_seconds += self._month_offset[self.month] * 24 * 60 * 60
+ # The greogrian calendar
+ if self.calendarmodel == 'http://www.wikidata.org/entity/Q1985727':
+ if (self.year % 400 == 0
+ or (self.year % 4 == 0 and self.year % 100 != 0)
+ and self.month > 2):
+ elapsed_seconds += 24 * 60 * 60 # Leap year
+ # The julian calendar
+ if self.calendarmodel == 'http://www.wikidata.org/entity/Q1985786':
+ if self.year % 4 == 0 and self.month > 2:
+ elapsed_seconds += 24 * 60 * 60
+ if self.day > 1:
+ # Days start at 1, not 0.
+ elapsed_seconds += (self.day - 1) * 24 * 60 * 60
+ elapsed_seconds += self.hour * 60 * 60
+ elapsed_seconds += self.minute * 60
+ elapsed_seconds += self.second
+ if self.timezone is not None:
+ elapsed_seconds += self.timezone * 60
+ return elapsed_seconds
+
+ def __lt__(self, other):
+ """Compare if self is less than other."""
+ return self._getSecondsAdjusted() < other._getSecondsAdjusted()
+
+ def __le__(self, other):
+ """Compare if self is less equals other."""
+ return self._getSecondsAdjusted() <= other._getSecondsAdjusted()
+
+ def __gt__(self, other):
+ """Compare if self is greater than other."""
+ return self._getSecondsAdjusted() > other._getSecondsAdjusted()
+
+ def __ge__(self, other):
+ """Compare if self is greater equals other."""
+ return self._getSecondsAdjusted() >= other._getSecondsAdjusted()
+
@classmethod
def fromTimestr(cls: Type['WbTime'],
datetimestr: str,
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index c97f6f7..3867219 100755
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -378,6 +378,37 @@
with self.assertRaisesRegex(ValueError, regex):
pywikibot.WbTime(site=repo, precision='invalid_precision')
+ def test_comparison(self):
+ """Test WbTime comparison."""
+ repo = self.get_repo()
+ t1 = pywikibot.WbTime(site=repo, year=2010, hour=12, minute=43)
+ t2 = pywikibot.WbTime(site=repo, year=-2005, hour=16, minute=45)
+ self.assertEqual(t1.precision, pywikibot.WbTime.PRECISION['minute'])
+ self.assertEqual(t1, t1)
+ self.assertGreaterEqual(t1, t1)
+ self.assertGreaterEqual(t1, t2)
+ self.assertGreater(t1, t2)
+ self.assertEqual(t1.year, 2010)
+ self.assertEqual(t2.year, -2005)
+ self.assertEqual(t1.month, 1)
+ self.assertEqual(t2.month, 1)
+ self.assertEqual(t1.day, 1)
+ self.assertEqual(t2.day, 1)
+ self.assertEqual(t1.hour, 12)
+ self.assertEqual(t2.hour, 16)
+ self.assertEqual(t1.minute, 43)
+ self.assertEqual(t2.minute, 45)
+ self.assertEqual(t1.second, 0)
+ self.assertEqual(t2.second, 0)
+ self.assertEqual(t1.toTimestr(), '+00000002010-01-01T12:43:00Z')
+ self.assertEqual(t2.toTimestr(), '-00000002005-01-01T16:45:00Z')
+ self.assertRaises(ValueError, pywikibot.WbTime, site=repo,
+ precision=15)
+ self.assertRaises(ValueError, pywikibot.WbTime, site=repo,
+ precision='invalid_precision')
+ self.assertIsInstance(t1.toTimestamp(), pywikibot.Timestamp)
+ self.assertRaises(ValueError, t2.toTimestamp)
+
class TestWbQuantity(WbRepresentationTestCase):
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/863328
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I694886fd4b264e97c351a8b2a5aefd2b5878be69
Gerrit-Change-Number: 863328
Gerrit-PatchSet: 17
Gerrit-Owner: RPI2026F1 <sarkaraoyan+rpi2026f1(a)gmail.com>
Gerrit-Reviewer: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: RPI2026F1 <sarkaraoyan+rpi2026f1(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged