commit
0d2f5c97d9
12 changed files with 227 additions and 654 deletions
11
.gitattributes
vendored
Normal file
11
.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: Unlicense
|
||||
|
||||
.py text eol=lf
|
||||
.rst text eol=lf
|
||||
.txt text eol=lf
|
||||
.yaml text eol=lf
|
||||
.toml text eol=lf
|
||||
.license text eol=lf
|
||||
.md text eol=lf
|
||||
|
|
@ -1,42 +1,21 @@
|
|||
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò
|
||||
# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: Unlicense
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/python/black
|
||||
rev: 23.3.0
|
||||
hooks:
|
||||
- id: black
|
||||
- repo: https://github.com/fsfe/reuse-tool
|
||||
rev: v1.1.2
|
||||
hooks:
|
||||
- id: reuse
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.4.0
|
||||
rev: v4.5.0
|
||||
hooks:
|
||||
- id: check-yaml
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- repo: https://github.com/pycqa/pylint
|
||||
rev: v2.17.4
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.3.4
|
||||
hooks:
|
||||
- id: pylint
|
||||
name: pylint (library code)
|
||||
types: [python]
|
||||
args:
|
||||
- --disable=consider-using-f-string
|
||||
exclude: "^(docs/|examples/|tests/|setup.py$)"
|
||||
- id: pylint
|
||||
name: pylint (example code)
|
||||
description: Run pylint rules on "examples/*.py" files
|
||||
types: [python]
|
||||
files: "^examples/"
|
||||
args:
|
||||
- --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code
|
||||
- id: pylint
|
||||
name: pylint (test code)
|
||||
description: Run pylint rules on "tests/*.py" files
|
||||
types: [python]
|
||||
files: "^tests/"
|
||||
args:
|
||||
- --disable=missing-docstring,consider-using-f-string,duplicate-code
|
||||
- id: ruff-format
|
||||
- id: ruff
|
||||
args: ["--fix"]
|
||||
- repo: https://github.com/fsfe/reuse-tool
|
||||
rev: v3.0.1
|
||||
hooks:
|
||||
- id: reuse
|
||||
|
|
|
|||
399
.pylintrc
399
.pylintrc
|
|
@ -1,399 +0,0 @@
|
|||
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: Unlicense
|
||||
|
||||
[MASTER]
|
||||
|
||||
# A comma-separated list of package or module names from where C extensions may
|
||||
# be loaded. Extensions are loading into the active Python interpreter and may
|
||||
# run arbitrary code
|
||||
extension-pkg-whitelist=
|
||||
|
||||
# Add files or directories to the ignore-list. They should be base names, not
|
||||
# paths.
|
||||
ignore=CVS
|
||||
|
||||
# Add files or directories matching the regex patterns to the ignore-list. The
|
||||
# regex matches against base names, not paths.
|
||||
ignore-patterns=
|
||||
|
||||
# Python code to execute, usually for sys.path manipulation such as
|
||||
# pygtk.require().
|
||||
#init-hook=
|
||||
|
||||
# Use multiple processes to speed up Pylint.
|
||||
jobs=1
|
||||
|
||||
# List of plugins (as comma separated values of python modules names) to load,
|
||||
# usually to register additional checkers.
|
||||
load-plugins=pylint.extensions.no_self_use
|
||||
|
||||
# Pickle collected data for later comparisons.
|
||||
persistent=yes
|
||||
|
||||
# Specify a configuration file.
|
||||
#rcfile=
|
||||
|
||||
# Allow loading of arbitrary C extensions. Extensions are imported into the
|
||||
# active Python interpreter and may run arbitrary code.
|
||||
unsafe-load-any-extension=no
|
||||
|
||||
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Only show warnings with the listed confidence levels. Leave empty to show
|
||||
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
|
||||
confidence=
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifiers separated by comma (,) or put this
|
||||
# option multiple times (only on the command line, not in the configuration
|
||||
# file where it should appear only once).You can also use "--disable=all" to
|
||||
# disable everything first and then reenable specific checks. For example, if
|
||||
# you want to run only the similarities checker, you can use "--disable=all
|
||||
# --enable=similarities". If you want to run only the classes checker, but have
|
||||
# no Warning level messages displayed, use"--disable=all --enable=classes
|
||||
# --disable=W"
|
||||
# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call
|
||||
disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding
|
||||
|
||||
# Enable the message, report, category or checker with the given id(s). You can
|
||||
# either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once). See also the "--disable" option for examples.
|
||||
enable=
|
||||
|
||||
|
||||
[REPORTS]
|
||||
|
||||
# Python expression which should return a note less than 10 (10 is the highest
|
||||
# note). You have access to the variables errors warning, statement which
|
||||
# respectively contain the number of errors / warnings messages and the total
|
||||
# number of statements analyzed. This is used by the global evaluation report
|
||||
# (RP0004).
|
||||
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
|
||||
|
||||
# Template used to display messages. This is a python new-style format string
|
||||
# used to format the message information. See doc for all details
|
||||
#msg-template=
|
||||
|
||||
# Set the output format. Available formats are text, parseable, colorized, json
|
||||
# and msvs (visual studio).You can also give a reporter class, eg
|
||||
# mypackage.mymodule.MyReporterClass.
|
||||
output-format=text
|
||||
|
||||
# Tells whether to display a full report or only the messages
|
||||
reports=no
|
||||
|
||||
# Activate the evaluation score.
|
||||
score=yes
|
||||
|
||||
|
||||
[REFACTORING]
|
||||
|
||||
# Maximum number of nested blocks for function / method body
|
||||
max-nested-blocks=5
|
||||
|
||||
|
||||
[LOGGING]
|
||||
|
||||
# Logging modules to check that the string format arguments are in logging
|
||||
# function parameter format
|
||||
logging-modules=logging
|
||||
|
||||
|
||||
[SPELLING]
|
||||
|
||||
# Spelling dictionary name. Available dictionaries: none. To make it working
|
||||
# install python-enchant package.
|
||||
spelling-dict=
|
||||
|
||||
# List of comma separated words that should not be checked.
|
||||
spelling-ignore-words=
|
||||
|
||||
# A path to a file that contains private dictionary; one word per line.
|
||||
spelling-private-dict-file=
|
||||
|
||||
# Tells whether to store unknown words to indicated private dictionary in
|
||||
# --spelling-private-dict-file option instead of raising a message.
|
||||
spelling-store-unknown-words=no
|
||||
|
||||
|
||||
[MISCELLANEOUS]
|
||||
|
||||
# List of note tags to take in consideration, separated by a comma.
|
||||
# notes=FIXME,XXX,TODO
|
||||
notes=FIXME,XXX
|
||||
|
||||
|
||||
[TYPECHECK]
|
||||
|
||||
# List of decorators that produce context managers, such as
|
||||
# contextlib.contextmanager. Add to this list to register other decorators that
|
||||
# produce valid context managers.
|
||||
contextmanager-decorators=contextlib.contextmanager
|
||||
|
||||
# List of members which are set dynamically and missed by pylint inference
|
||||
# system, and so shouldn't trigger E1101 when accessed. Python regular
|
||||
# expressions are accepted.
|
||||
generated-members=
|
||||
|
||||
# Tells whether missing members accessed in mixin class should be ignored. A
|
||||
# mixin class is detected if its name ends with "mixin" (case insensitive).
|
||||
ignore-mixin-members=yes
|
||||
|
||||
# This flag controls whether pylint should warn about no-member and similar
|
||||
# checks whenever an opaque object is returned when inferring. The inference
|
||||
# can return multiple potential results while evaluating a Python object, but
|
||||
# some branches might not be evaluated, which results in partial inference. In
|
||||
# that case, it might be useful to still emit no-member and other checks for
|
||||
# the rest of the inferred objects.
|
||||
ignore-on-opaque-inference=yes
|
||||
|
||||
# List of class names for which member attributes should not be checked (useful
|
||||
# for classes with dynamically set attributes). This supports the use of
|
||||
# qualified names.
|
||||
ignored-classes=optparse.Values,thread._local,_thread._local
|
||||
|
||||
# List of module names for which member attributes should not be checked
|
||||
# (useful for modules/projects where namespaces are manipulated during runtime
|
||||
# and thus existing member attributes cannot be deduced by static analysis. It
|
||||
# supports qualified module names, as well as Unix pattern matching.
|
||||
ignored-modules=board
|
||||
|
||||
# Show a hint with possible names when a member name was not found. The aspect
|
||||
# of finding the hint is based on edit distance.
|
||||
missing-member-hint=yes
|
||||
|
||||
# The minimum edit distance a name should have in order to be considered a
|
||||
# similar match for a missing member name.
|
||||
missing-member-hint-distance=1
|
||||
|
||||
# The total number of similar names that should be taken in consideration when
|
||||
# showing a hint for a missing member.
|
||||
missing-member-max-choices=1
|
||||
|
||||
|
||||
[VARIABLES]
|
||||
|
||||
# List of additional names supposed to be defined in builtins. Remember that
|
||||
# you should avoid to define new builtins when possible.
|
||||
additional-builtins=
|
||||
|
||||
# Tells whether unused global variables should be treated as a violation.
|
||||
allow-global-unused-variables=yes
|
||||
|
||||
# List of strings which can identify a callback function by name. A callback
|
||||
# name must start or end with one of those strings.
|
||||
callbacks=cb_,_cb
|
||||
|
||||
# A regular expression matching the name of dummy variables (i.e. expectedly
|
||||
# not used).
|
||||
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
|
||||
|
||||
# Argument names that match this expression will be ignored. Default to name
|
||||
# with leading underscore
|
||||
ignored-argument-names=_.*|^ignored_|^unused_
|
||||
|
||||
# Tells whether we should check for unused import in __init__ files.
|
||||
init-import=no
|
||||
|
||||
# List of qualified module names which can have objects that can redefine
|
||||
# builtins.
|
||||
redefining-builtins-modules=six.moves,future.builtins
|
||||
|
||||
|
||||
[FORMAT]
|
||||
|
||||
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
|
||||
# expected-line-ending-format=
|
||||
expected-line-ending-format=LF
|
||||
|
||||
# Regexp for a line that is allowed to be longer than the limit.
|
||||
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
|
||||
|
||||
# Number of spaces of indent required inside a hanging or continued line.
|
||||
indent-after-paren=4
|
||||
|
||||
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
|
||||
# tab).
|
||||
indent-string=' '
|
||||
|
||||
# Maximum number of characters on a single line.
|
||||
max-line-length=100
|
||||
|
||||
# Maximum number of lines in a module
|
||||
max-module-lines=1000
|
||||
|
||||
# Allow the body of a class to be on the same line as the declaration if body
|
||||
# contains single statement.
|
||||
single-line-class-stmt=no
|
||||
|
||||
# Allow the body of an if to be on the same line as the test if there is no
|
||||
# else.
|
||||
single-line-if-stmt=no
|
||||
|
||||
|
||||
[SIMILARITIES]
|
||||
|
||||
# Ignore comments when computing similarities.
|
||||
ignore-comments=yes
|
||||
|
||||
# Ignore docstrings when computing similarities.
|
||||
ignore-docstrings=yes
|
||||
|
||||
# Ignore imports when computing similarities.
|
||||
ignore-imports=yes
|
||||
|
||||
# Minimum lines number of a similarity.
|
||||
min-similarity-lines=12
|
||||
|
||||
|
||||
[BASIC]
|
||||
|
||||
# Regular expression matching correct argument names
|
||||
argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
|
||||
|
||||
# Regular expression matching correct attribute names
|
||||
attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
|
||||
|
||||
# Bad variable names which should always be refused, separated by a comma
|
||||
bad-names=foo,bar,baz,toto,tutu,tata
|
||||
|
||||
# Regular expression matching correct class attribute names
|
||||
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
|
||||
|
||||
# Regular expression matching correct class names
|
||||
# class-rgx=[A-Z_][a-zA-Z0-9]+$
|
||||
class-rgx=[A-Z_][a-zA-Z0-9_]+$
|
||||
|
||||
# Regular expression matching correct constant names
|
||||
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
|
||||
|
||||
# Minimum line length for functions/classes that require docstrings, shorter
|
||||
# ones are exempt.
|
||||
docstring-min-length=-1
|
||||
|
||||
# Regular expression matching correct function names
|
||||
function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
|
||||
|
||||
# Good variable names which should always be accepted, separated by a comma
|
||||
# good-names=i,j,k,ex,Run,_
|
||||
good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_
|
||||
|
||||
# Include a hint for the correct naming format with invalid-name
|
||||
include-naming-hint=no
|
||||
|
||||
# Regular expression matching correct inline iteration names
|
||||
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
|
||||
|
||||
# Regular expression matching correct method names
|
||||
method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
|
||||
|
||||
# Regular expression matching correct module names
|
||||
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
|
||||
|
||||
# Colon-delimited sets of names that determine each other's naming style when
|
||||
# the name regexes allow several styles.
|
||||
name-group=
|
||||
|
||||
# Regular expression which should only match function or class names that do
|
||||
# not require a docstring.
|
||||
no-docstring-rgx=^_
|
||||
|
||||
# List of decorators that produce properties, such as abc.abstractproperty. Add
|
||||
# to this list to register other decorators that produce valid properties.
|
||||
property-classes=abc.abstractproperty
|
||||
|
||||
# Regular expression matching correct variable names
|
||||
variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
|
||||
|
||||
|
||||
[IMPORTS]
|
||||
|
||||
# Allow wildcard imports from modules that define __all__.
|
||||
allow-wildcard-with-all=no
|
||||
|
||||
# Analyse import fallback blocks. This can be used to support both Python 2 and
|
||||
# 3 compatible code, which means that the block might have code that exists
|
||||
# only in one or another interpreter, leading to false positives when analysed.
|
||||
analyse-fallback-blocks=no
|
||||
|
||||
# Deprecated modules which should not be used, separated by a comma
|
||||
deprecated-modules=optparse,tkinter.tix
|
||||
|
||||
# Create a graph of external dependencies in the given file (report RP0402 must
|
||||
# not be disabled)
|
||||
ext-import-graph=
|
||||
|
||||
# Create a graph of every (i.e. internal and external) dependencies in the
|
||||
# given file (report RP0402 must not be disabled)
|
||||
import-graph=
|
||||
|
||||
# Create a graph of internal dependencies in the given file (report RP0402 must
|
||||
# not be disabled)
|
||||
int-import-graph=
|
||||
|
||||
# Force import order to recognize a module as part of the standard
|
||||
# compatibility libraries.
|
||||
known-standard-library=
|
||||
|
||||
# Force import order to recognize a module as part of a third party library.
|
||||
known-third-party=enchant
|
||||
|
||||
|
||||
[CLASSES]
|
||||
|
||||
# List of method names used to declare (i.e. assign) instance attributes.
|
||||
defining-attr-methods=__init__,__new__,setUp
|
||||
|
||||
# List of member names, which should be excluded from the protected access
|
||||
# warning.
|
||||
exclude-protected=_asdict,_fields,_replace,_source,_make
|
||||
|
||||
# List of valid names for the first argument in a class method.
|
||||
valid-classmethod-first-arg=cls
|
||||
|
||||
# List of valid names for the first argument in a metaclass class method.
|
||||
valid-metaclass-classmethod-first-arg=mcs
|
||||
|
||||
|
||||
[DESIGN]
|
||||
|
||||
# Maximum number of arguments for function / method
|
||||
max-args=5
|
||||
|
||||
# Maximum number of attributes for a class (see R0902).
|
||||
# max-attributes=7
|
||||
max-attributes=11
|
||||
|
||||
# Maximum number of boolean expressions in a if statement
|
||||
max-bool-expr=5
|
||||
|
||||
# Maximum number of branch for function / method body
|
||||
max-branches=12
|
||||
|
||||
# Maximum number of locals for function / method body
|
||||
max-locals=15
|
||||
|
||||
# Maximum number of parents for a class (see R0901).
|
||||
max-parents=7
|
||||
|
||||
# Maximum number of public methods for a class (see R0904).
|
||||
max-public-methods=20
|
||||
|
||||
# Maximum number of return / yield for function / method body
|
||||
max-returns=6
|
||||
|
||||
# Maximum number of statements in function / method body
|
||||
max-statements=50
|
||||
|
||||
# Minimum number of public methods for a class (see R0903).
|
||||
min-public-methods=1
|
||||
|
||||
|
||||
[EXCEPTIONS]
|
||||
|
||||
# Exceptions that will emit a warning when being caught. Defaults to
|
||||
# "Exception"
|
||||
overgeneral-exceptions=builtins.Exception
|
||||
|
|
@ -13,9 +13,9 @@ Introduction
|
|||
:target: https://github.com/adafruit/Adafruit_CircuitPython_datetime/actions
|
||||
:alt: Build Status
|
||||
|
||||
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
|
||||
:target: https://github.com/psf/black
|
||||
:alt: Code Style: Black
|
||||
.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
|
||||
:target: https://github.com/astral-sh/ruff
|
||||
:alt: Code Style: Ruff
|
||||
|
||||
Basic date and time types. Implements a subset of the `CPython datetime module <https://docs.python.org/3/library/datetime.html>`_.
|
||||
|
||||
|
|
|
|||
|
|
@ -26,14 +26,15 @@ Implementation Notes
|
|||
|
||||
|
||||
"""
|
||||
# pylint: disable=too-many-lines
|
||||
import time as _time
|
||||
|
||||
import math as _math
|
||||
import re as _re
|
||||
import time as _time
|
||||
|
||||
from micropython import const
|
||||
|
||||
try:
|
||||
from typing import Any, Union, Optional, Tuple, Sequence, List
|
||||
from typing import Any, List, Optional, Sequence, Tuple, Union
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
|
@ -76,18 +77,12 @@ def _cmp(obj_x: Any, obj_y: Any) -> int:
|
|||
return 0 if obj_x == obj_y else 1 if obj_x > obj_y else -1
|
||||
|
||||
|
||||
def _cmperror(
|
||||
obj_x: Union["datetime", "timedelta"], obj_y: Union["datetime", "timedelta"]
|
||||
) -> None:
|
||||
raise TypeError(
|
||||
"can't compare '%s' to '%s'" % (type(obj_x).__name__, type(obj_y).__name__)
|
||||
)
|
||||
def _cmperror(obj_x: Union["datetime", "timedelta"], obj_y: Union["datetime", "timedelta"]) -> None:
|
||||
raise TypeError(f"can't compare '{type(obj_x).__name__}' to '{type(obj_y).__name__}'")
|
||||
|
||||
|
||||
# Utility functions - time
|
||||
def _check_time_fields(
|
||||
hour: int, minute: int, second: int, microsecond: int, fold: int
|
||||
) -> None:
|
||||
def _check_time_fields(hour: int, minute: int, second: int, microsecond: int, fold: int) -> None:
|
||||
if not isinstance(hour, int):
|
||||
raise TypeError("Hour expected as int")
|
||||
if not 0 <= hour <= 23:
|
||||
|
|
@ -98,32 +93,25 @@ def _check_time_fields(
|
|||
raise ValueError("second must be in 0..59", second)
|
||||
if not 0 <= microsecond <= 999999:
|
||||
raise ValueError("microsecond must be in 0..999999", microsecond)
|
||||
if fold not in (0, 1): # from CPython API
|
||||
if fold not in {0, 1}: # from CPython API
|
||||
raise ValueError("fold must be either 0 or 1", fold)
|
||||
|
||||
|
||||
def _check_utc_offset(name: str, offset: "timedelta") -> None:
|
||||
assert name in ("utcoffset", "dst")
|
||||
assert name in {"utcoffset", "dst"}
|
||||
if offset is None:
|
||||
return
|
||||
if not isinstance(offset, timedelta):
|
||||
raise TypeError(
|
||||
"tzinfo.%s() must return None "
|
||||
"or timedelta, not '%s'" % (name, type(offset))
|
||||
)
|
||||
raise TypeError(f"tzinfo.{name}() must return None or timedelta, not '{type(offset)}'")
|
||||
if offset % timedelta(minutes=1) or offset.microseconds:
|
||||
raise ValueError(
|
||||
"tzinfo.%s() must return a whole number "
|
||||
"of minutes, got %s" % (name, offset)
|
||||
)
|
||||
raise ValueError(f"tzinfo.{name}() must return a whole number of minutes, got {offset}")
|
||||
if not -timedelta(1) < offset < timedelta(1):
|
||||
raise ValueError(
|
||||
"%s()=%s, must be must be strictly between"
|
||||
" -timedelta(hours=24) and timedelta(hours=24)" % (name, offset)
|
||||
f"{name}()={offset}, must be must be strictly between"
|
||||
" -timedelta(hours=24) and timedelta(hours=24)"
|
||||
)
|
||||
|
||||
|
||||
# pylint: disable=invalid-name
|
||||
def _format_offset(off: "timedelta") -> str:
|
||||
s = ""
|
||||
if off is not None:
|
||||
|
|
@ -134,12 +122,12 @@ def _format_offset(off: "timedelta") -> str:
|
|||
sign = "+"
|
||||
hh, mm = divmod(off, timedelta(hours=1))
|
||||
mm, ss = divmod(mm, timedelta(minutes=1))
|
||||
s += "%s%02d:%02d" % (sign, hh, mm)
|
||||
s += f"{sign}{hh:02d}:{mm:02d}"
|
||||
if ss or ss.microseconds:
|
||||
s += ":%02d" % ss.seconds
|
||||
s += f":{ss.seconds:02d}"
|
||||
|
||||
if ss.microseconds:
|
||||
s += ".%06d" % ss.microseconds
|
||||
s += f".{ss.microseconds:06d}"
|
||||
return s
|
||||
|
||||
|
||||
|
|
@ -147,9 +135,7 @@ def _format_offset(off: "timedelta") -> str:
|
|||
def _check_tzname(name: Optional[str]) -> None:
|
||||
""" "Just raise TypeError if the arg isn't None or a string."""
|
||||
if name is not None and not isinstance(name, str):
|
||||
raise TypeError(
|
||||
"tzinfo.tzname() must return None or string, " "not '%s'" % type(name)
|
||||
)
|
||||
raise TypeError("tzinfo.tzname() must return None or string, " "not '%s'" % type(name))
|
||||
|
||||
|
||||
def _check_tzinfo_arg(time_zone: Optional["tzinfo"]):
|
||||
|
|
@ -203,7 +189,6 @@ def _ymd2ord(year: int, month: int, day: int) -> int:
|
|||
return _days_before_year(year) + _days_before_month(year, month) + day
|
||||
|
||||
|
||||
# pylint: disable=too-many-arguments
|
||||
def _build_struct_time(
|
||||
tm_year: int,
|
||||
tm_month: int,
|
||||
|
|
@ -230,7 +215,6 @@ def _build_struct_time(
|
|||
)
|
||||
|
||||
|
||||
# pylint: disable=invalid-name
|
||||
def _format_time(hh: int, mm: int, ss: int, us: int, timespec: str = "auto") -> str:
|
||||
if timespec != "auto":
|
||||
raise NotImplementedError("Only default timespec supported")
|
||||
|
|
@ -321,7 +305,6 @@ def _ord2ymd(n: int) -> Tuple[int, int, int]:
|
|||
class timedelta:
|
||||
"""A timedelta object represents a duration, the difference between two dates or times."""
|
||||
|
||||
# pylint: disable=too-many-arguments, too-many-locals, too-many-statements
|
||||
def __new__(
|
||||
cls,
|
||||
days: int = 0,
|
||||
|
|
@ -459,31 +442,28 @@ class timedelta:
|
|||
def __repr__(self) -> str:
|
||||
args = []
|
||||
if self._days:
|
||||
args.append("days=%d" % self._days)
|
||||
args.append(f"days={self._days}")
|
||||
if self._seconds:
|
||||
args.append("seconds=%d" % self._seconds)
|
||||
args.append(f"seconds={self._seconds}")
|
||||
if self._microseconds:
|
||||
args.append("microseconds=%d" % self._microseconds)
|
||||
args.append(f"microseconds={self._microseconds}")
|
||||
if not args:
|
||||
args.append("0")
|
||||
return "%s.%s(%s)" % (
|
||||
self.__class__.__module__,
|
||||
self.__class__.__qualname__,
|
||||
", ".join(args),
|
||||
)
|
||||
return f"{self.__class__.__module__}.{self.__class__.__qualname__}({', '.join(args)})"
|
||||
|
||||
def __str__(self) -> str:
|
||||
mm, ss = divmod(self._seconds, 60)
|
||||
hh, mm = divmod(mm, 60)
|
||||
s = "%d:%02d:%02d" % (hh, mm, ss)
|
||||
s = f"{hh}:{mm:02d}:{ss:02d}"
|
||||
if self._days:
|
||||
|
||||
def plural(n):
|
||||
return n, abs(n) != 1 and "s" or ""
|
||||
|
||||
s = ("%d day%s, " % plural(self._days)) + s
|
||||
days, suffix = plural(self._days)
|
||||
s = f"{days} day{suffix}, {s}"
|
||||
if self._microseconds:
|
||||
s = s + ".%06d" % self._microseconds
|
||||
s = f"{s}.{self._microseconds:06d}"
|
||||
return s
|
||||
|
||||
# Supported operations
|
||||
|
|
@ -535,9 +515,7 @@ class timedelta:
|
|||
if isinstance(other, int):
|
||||
# for CPython compatibility, we cannot use
|
||||
# our __class__ here, but need a real timedelta
|
||||
return timedelta(
|
||||
self._days * other, self._seconds * other, self._microseconds * other
|
||||
)
|
||||
return timedelta(self._days * other, self._seconds * other, self._microseconds * other)
|
||||
if isinstance(other, float):
|
||||
# a, b = other.as_integer_ratio()
|
||||
# return self * a / b
|
||||
|
|
@ -578,7 +556,6 @@ class timedelta:
|
|||
_cmperror(self, other)
|
||||
return self._cmp(other) > 0
|
||||
|
||||
# pylint: disable=no-self-use, protected-access
|
||||
def _cmp(self, other: "timedelta") -> int:
|
||||
assert isinstance(other, timedelta)
|
||||
return _cmp(self._getstate(), other._getstate())
|
||||
|
|
@ -590,7 +567,6 @@ class timedelta:
|
|||
return (self._days, self._seconds, self._microseconds)
|
||||
|
||||
|
||||
# pylint: disable=no-self-use
|
||||
class tzinfo:
|
||||
"""This is an abstract base class, meaning that this class should not
|
||||
be instantiated directly. Define a subclass of tzinfo to capture information
|
||||
|
|
@ -609,15 +585,13 @@ class tzinfo:
|
|||
"""Return the time zone name corresponding to the datetime object dt, as a string."""
|
||||
raise NotImplementedError("tzinfo subclass must override tzname()")
|
||||
|
||||
def dst(self, dt: "datetime") -> None: # pylint: disable=unused-argument
|
||||
def dst(self, dt: "datetime") -> None:
|
||||
"""Return the DST setting correspinding to the datetime object dt, as a number.
|
||||
|
||||
DST usage is currently not implemented for this library.
|
||||
"""
|
||||
return None
|
||||
|
||||
# tzinfo is an abstract base class, disabling for self._offset
|
||||
# pylint: disable=no-member
|
||||
def fromutc(self, dt: "datetime") -> "datetime":
|
||||
"datetime in UTC -> datetime in local time."
|
||||
|
||||
|
|
@ -696,9 +670,7 @@ class date:
|
|||
Valid format is ``YYYY-MM-DD``
|
||||
|
||||
"""
|
||||
match = _re.match(
|
||||
r"([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$", date_string
|
||||
)
|
||||
match = _re.match(r"([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$", date_string)
|
||||
if match:
|
||||
y, m, d = int(match.group(1)), int(match.group(2)), int(match.group(3))
|
||||
return cls(y, m, d)
|
||||
|
|
@ -748,19 +720,14 @@ class date:
|
|||
|
||||
def isoformat(self) -> str:
|
||||
"""Return a string representing the date in ISO 8601 format, YYYY-MM-DD:"""
|
||||
return "%04d-%02d-%02d" % (self._year, self._month, self._day)
|
||||
return f"{self._year:04d}-{self._month:02d}-{self._day:02d}"
|
||||
|
||||
# For a date d, str(d) is equivalent to d.isoformat()
|
||||
__str__ = isoformat
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Convert to formal string, for repr()."""
|
||||
return "%s(%d, %d, %d)" % (
|
||||
"datetime." + self.__class__.__name__,
|
||||
self._year,
|
||||
self._month,
|
||||
self._day,
|
||||
)
|
||||
return f"datetime.{self.__class__.__name__}({self._year}, {self._month}, {self._day})"
|
||||
|
||||
# Supported comparisons
|
||||
def __eq__(self, other: "date") -> bool:
|
||||
|
|
@ -822,9 +789,7 @@ class timezone(tzinfo):
|
|||
# Sentinel value to disallow None
|
||||
_Omitted = object()
|
||||
|
||||
def __new__(
|
||||
cls, offset: timedelta, name: Union[str, object] = _Omitted
|
||||
) -> "timezone":
|
||||
def __new__(cls, offset: timedelta, name: Union[str, object] = _Omitted) -> "timezone":
|
||||
if not isinstance(offset, timedelta):
|
||||
raise TypeError("offset must be a timedelta")
|
||||
if name is cls._Omitted:
|
||||
|
|
@ -840,14 +805,11 @@ class timezone(tzinfo):
|
|||
" timedelta(hours=24)."
|
||||
)
|
||||
if offset.microseconds != 0 or offset.seconds % 60 != 0:
|
||||
raise ValueError(
|
||||
"offset must be a timedelta representing a whole number of minutes"
|
||||
)
|
||||
raise ValueError("offset must be a timedelta representing a whole number of minutes")
|
||||
cls._offset = offset
|
||||
cls._name = name
|
||||
return cls._create(offset, name)
|
||||
|
||||
# pylint: disable=protected-access, bad-super-call
|
||||
@classmethod
|
||||
def _create(cls, offset: timedelta, name: Optional[str] = None) -> "timezone":
|
||||
"""High-level creation for a timezone object."""
|
||||
|
|
@ -883,12 +845,8 @@ class timezone(tzinfo):
|
|||
if self is self.utc:
|
||||
return "datetime.timezone.utc"
|
||||
if self._name is None:
|
||||
return "%s(%r)" % ("datetime." + self.__class__.__name__, self._offset)
|
||||
return "%s(%r, %r)" % (
|
||||
"datetime." + self.__class__.__name__,
|
||||
self._offset,
|
||||
self._name,
|
||||
)
|
||||
return f"datetime.{self.__class__.__name__}({self._offset!r})"
|
||||
return f"datetime.{self.__class__.__name__}({self._offset!r}, {self._name!r})"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.tzname(None)
|
||||
|
|
@ -902,7 +860,7 @@ class timezone(tzinfo):
|
|||
sign = "+"
|
||||
hours, rest = divmod(delta, timedelta(hours=1))
|
||||
minutes = rest // timedelta(minutes=1)
|
||||
return "UTC{}{:02d}:{:02d}".format(sign, hours, minutes)
|
||||
return f"UTC{sign}{hours:02d}:{minutes:02d}"
|
||||
|
||||
maxoffset = timedelta(hours=23, minutes=59)
|
||||
minoffset = -maxoffset
|
||||
|
|
@ -914,7 +872,6 @@ class time:
|
|||
|
||||
"""
|
||||
|
||||
# pylint: disable=redefined-outer-name
|
||||
def __new__(
|
||||
cls,
|
||||
hour: int = 0,
|
||||
|
|
@ -987,7 +944,6 @@ class time:
|
|||
raise ValueError()
|
||||
return results
|
||||
|
||||
# pylint: disable=too-many-locals
|
||||
@classmethod
|
||||
def fromisoformat(cls, time_string: str) -> "time":
|
||||
"""Return a time object constructed from an ISO date format.
|
||||
|
|
@ -1074,9 +1030,7 @@ class time:
|
|||
HH:MM:SS+HH:MM[:SS[.ffffff]], if microsecond is 0 and utcoffset() does not return None
|
||||
|
||||
"""
|
||||
s = _format_time(
|
||||
self._hour, self._minute, self._second, self._microsecond, timespec
|
||||
)
|
||||
s = _format_time(self._hour, self._minute, self._second, self._microsecond, timespec)
|
||||
tz = self._tzstr()
|
||||
if tz:
|
||||
s += tz
|
||||
|
|
@ -1195,31 +1149,26 @@ class time:
|
|||
assert not mm % timedelta(minutes=1), "whole minute"
|
||||
mm //= timedelta(minutes=1)
|
||||
assert 0 <= hh < 24
|
||||
off = "%s%02d%s%02d" % (sign, hh, sep, mm)
|
||||
off = f"{sign}{hh:02d}{sep}{mm:02d}"
|
||||
return off
|
||||
|
||||
def __format__(self, fmt: str) -> str:
|
||||
if not isinstance(fmt, str):
|
||||
raise TypeError("must be str, not %s" % type(fmt).__name__)
|
||||
raise TypeError(f"must be str, not {type(fmt).__name__}")
|
||||
return str(self)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Convert to formal string, for repr()."""
|
||||
if self._microsecond != 0:
|
||||
s = ", %d, %d" % (self._second, self._microsecond)
|
||||
s = f", {self._second}, {self._microsecond}"
|
||||
elif self._second != 0:
|
||||
s = ", %d" % self._second
|
||||
s = f", {self._second}"
|
||||
else:
|
||||
s = ""
|
||||
s = "%s(%d, %d%s)" % (
|
||||
"datetime." + self.__class__.__name__,
|
||||
self._hour,
|
||||
self._minute,
|
||||
s,
|
||||
)
|
||||
s = f"datetime.{self.__class__.__name__}({self._hour}, {self._minute}{s})"
|
||||
if self._tzinfo is not None:
|
||||
assert s[-1:] == ")"
|
||||
s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
|
||||
s = f"{s[:-1]}, tzinfo={self._tzinfo!r})"
|
||||
return s
|
||||
|
||||
# Pickle support
|
||||
|
|
@ -1235,7 +1184,6 @@ class time:
|
|||
return (basestate,)
|
||||
|
||||
|
||||
# pylint: disable=too-many-instance-attributes, too-many-public-methods
|
||||
class datetime(date):
|
||||
"""A datetime object is a single object containing all the information
|
||||
from a date object and a time object. Like a date object, datetime assumes
|
||||
|
|
@ -1244,7 +1192,6 @@ class datetime(date):
|
|||
|
||||
"""
|
||||
|
||||
# pylint: disable=redefined-outer-name
|
||||
def __new__(
|
||||
cls,
|
||||
year: int,
|
||||
|
|
@ -1325,7 +1272,6 @@ class datetime(date):
|
|||
|
||||
# Class methods
|
||||
|
||||
# pylint: disable=protected-access
|
||||
@classmethod
|
||||
def _fromtimestamp(cls, t: float, utc: bool, tz: Optional["tzinfo"]) -> "datetime":
|
||||
"""Construct a datetime from a POSIX timestamp (like time.time()).
|
||||
|
|
@ -1344,9 +1290,7 @@ class datetime(date):
|
|||
us = 0
|
||||
|
||||
if utc:
|
||||
raise NotImplementedError(
|
||||
"CircuitPython does not currently implement time.gmtime."
|
||||
)
|
||||
raise NotImplementedError("CircuitPython does not currently implement time.gmtime.")
|
||||
converter = _time.localtime
|
||||
struct_time = converter(t)
|
||||
ss = min(struct_time[5], 59) # clamp out leap seconds if the platform has them
|
||||
|
|
@ -1364,11 +1308,8 @@ class datetime(date):
|
|||
result = tz.fromutc(result)
|
||||
return result
|
||||
|
||||
## pylint: disable=arguments-differ, arguments-renamed
|
||||
@classmethod
|
||||
def fromtimestamp(
|
||||
cls, timestamp: float, tz: Optional["tzinfo"] = None
|
||||
) -> "datetime":
|
||||
def fromtimestamp(cls, timestamp: float, tz: Optional["tzinfo"] = None) -> "datetime":
|
||||
return cls._fromtimestamp(timestamp, tz is not None, tz)
|
||||
|
||||
@classmethod
|
||||
|
|
@ -1532,15 +1473,7 @@ class datetime(date):
|
|||
def ctime(self) -> str:
|
||||
"Return string representing the datetime."
|
||||
weekday = self.toordinal() % 7 or 7
|
||||
return "%s %s %2d %02d:%02d:%02d %04d" % (
|
||||
_DAYNAMES[weekday],
|
||||
_MONTHNAMES[self._month],
|
||||
self._day,
|
||||
self._hour,
|
||||
self._minute,
|
||||
self._second,
|
||||
self._year,
|
||||
)
|
||||
return f"{_DAYNAMES[weekday]} {_MONTHNAMES[self._month]} {self._day:2d} {self._hour:02d}:{self._minute:02d}:{self._second:02d} {self._year:04d}" # noqa: E501
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""Convert to formal string, for repr()."""
|
||||
|
|
@ -1558,10 +1491,10 @@ class datetime(date):
|
|||
if L[-1] == 0:
|
||||
del L[-1]
|
||||
s = ", ".join(map(str, L))
|
||||
s = "%s(%s)" % ("datetime." + self.__class__.__name__, s)
|
||||
s = f"datetime.{self.__class__.__name__}({s})"
|
||||
if self._tzinfo is not None:
|
||||
assert s[-1:] == ")"
|
||||
s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
|
||||
s = f"{s[:-1]}, tzinfo={self._tzinfo!r})"
|
||||
return s
|
||||
|
||||
def isoformat(self, sep: str = "T", timespec: str = "auto") -> str:
|
||||
|
|
@ -1569,12 +1502,7 @@ class datetime(date):
|
|||
ISO8601 format.
|
||||
|
||||
"""
|
||||
s = "%04d-%02d-%02d%c" % (
|
||||
self._year,
|
||||
self._month,
|
||||
self._day,
|
||||
sep,
|
||||
) + _format_time(
|
||||
s = f"{self._year:04d}-{self._month:02d}-{self._day:02d}{sep}" + _format_time(
|
||||
self._hour, self._minute, self._second, self._microsecond, timespec
|
||||
)
|
||||
|
||||
|
|
@ -1625,9 +1553,7 @@ class datetime(date):
|
|||
tzinfo = self.tzinfo
|
||||
if fold is None:
|
||||
fold = self._fold
|
||||
return type(self)(
|
||||
year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold
|
||||
)
|
||||
return type(self)(year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold)
|
||||
|
||||
# Comparisons of datetime objects.
|
||||
def __eq__(self, other: Any) -> bool:
|
||||
|
|
@ -1738,9 +1664,7 @@ class datetime(date):
|
|||
days2 = other.toordinal()
|
||||
secs1 = self._second + self._minute * 60 + self._hour * 3600
|
||||
secs2 = other._second + other._minute * 60 + other._hour * 3600
|
||||
base = timedelta(
|
||||
days1 - days2, secs1 - secs2, self._microsecond - other._microsecond
|
||||
)
|
||||
base = timedelta(days1 - days2, secs1 - secs2, self._microsecond - other._microsecond)
|
||||
if self._tzinfo is other._tzinfo:
|
||||
return base
|
||||
myoff = self.utcoffset()
|
||||
|
|
@ -1760,9 +1684,7 @@ class datetime(date):
|
|||
else:
|
||||
days = _ymd2ord(self.year, self.month, self.day)
|
||||
seconds = self.hour * 3600 + self.minute * 60 + self.second
|
||||
self._hashcode = hash(
|
||||
timedelta(days, seconds, self.microsecond) - tzoff
|
||||
)
|
||||
self._hashcode = hash(timedelta(days, seconds, self.microsecond) - tzoff)
|
||||
return self._hashcode
|
||||
|
||||
def _getstate(self) -> Tuple[bytes]:
|
||||
|
|
@ -1793,7 +1715,6 @@ class datetime(date):
|
|||
|
||||
|
||||
# Module exports
|
||||
# pylint: disable=protected-access
|
||||
timezone.utc = timezone._create(timedelta(0))
|
||||
timezone.min = timezone._create(timezone.minoffset)
|
||||
timezone.max = timezone._create(timezone.maxoffset)
|
||||
|
|
|
|||
|
|
@ -4,5 +4,8 @@
|
|||
.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py)
|
||||
.. use this format as the module name: "adafruit_foo.foo"
|
||||
|
||||
API Reference
|
||||
#############
|
||||
|
||||
.. automodule:: adafruit_datetime
|
||||
:members:
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import sys
|
||||
import datetime
|
||||
|
||||
sys.path.insert(0, os.path.abspath(".."))
|
||||
|
||||
|
|
@ -51,9 +49,7 @@ project = "Adafruit datetime Library"
|
|||
creation_year = "2021"
|
||||
current_year = str(datetime.datetime.now().year)
|
||||
year_duration = (
|
||||
current_year
|
||||
if current_year == creation_year
|
||||
else creation_year + " - " + current_year
|
||||
current_year if current_year == creation_year else creation_year + " - " + current_year
|
||||
)
|
||||
copyright = year_duration + " Brent Rubell"
|
||||
author = "Brent Rubell"
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
|
||||
# Example of working with a `datetime` object
|
||||
# from https://docs.python.org/3/library/datetime.html#examples-of-usage-datetime
|
||||
from adafruit_datetime import datetime, date, time
|
||||
from adafruit_datetime import date, datetime, time
|
||||
|
||||
# Using datetime.combine()
|
||||
d = date(2005, 7, 14)
|
||||
|
|
|
|||
111
ruff.toml
Normal file
111
ruff.toml
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries
|
||||
#
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
target-version = "py38"
|
||||
line-length = 100
|
||||
|
||||
[lint]
|
||||
preview = true
|
||||
select = ["I", "PL", "UP"]
|
||||
|
||||
extend-select = [
|
||||
"D419", # empty-docstring
|
||||
"E501", # line-too-long
|
||||
"W291", # trailing-whitespace
|
||||
"PLC0414", # useless-import-alias
|
||||
"PLC2401", # non-ascii-name
|
||||
"PLC2801", # unnecessary-dunder-call
|
||||
"PLC3002", # unnecessary-direct-lambda-call
|
||||
"E999", # syntax-error
|
||||
"PLE0101", # return-in-init
|
||||
"F706", # return-outside-function
|
||||
"F704", # yield-outside-function
|
||||
"PLE0116", # continue-in-finally
|
||||
"PLE0117", # nonlocal-without-binding
|
||||
"PLE0241", # duplicate-bases
|
||||
"PLE0302", # unexpected-special-method-signature
|
||||
"PLE0604", # invalid-all-object
|
||||
"PLE0605", # invalid-all-format
|
||||
"PLE0643", # potential-index-error
|
||||
"PLE0704", # misplaced-bare-raise
|
||||
"PLE1141", # dict-iter-missing-items
|
||||
"PLE1142", # await-outside-async
|
||||
"PLE1205", # logging-too-many-args
|
||||
"PLE1206", # logging-too-few-args
|
||||
"PLE1307", # bad-string-format-type
|
||||
"PLE1310", # bad-str-strip-call
|
||||
"PLE1507", # invalid-envvar-value
|
||||
"PLE2502", # bidirectional-unicode
|
||||
"PLE2510", # invalid-character-backspace
|
||||
"PLE2512", # invalid-character-sub
|
||||
"PLE2513", # invalid-character-esc
|
||||
"PLE2514", # invalid-character-nul
|
||||
"PLE2515", # invalid-character-zero-width-space
|
||||
"PLR0124", # comparison-with-itself
|
||||
"PLR0202", # no-classmethod-decorator
|
||||
"PLR0203", # no-staticmethod-decorator
|
||||
"UP004", # useless-object-inheritance
|
||||
"PLR0206", # property-with-parameters
|
||||
"PLR0904", # too-many-public-methods
|
||||
"PLR0911", # too-many-return-statements
|
||||
"PLR0912", # too-many-branches
|
||||
"PLR0913", # too-many-arguments
|
||||
"PLR0914", # too-many-locals
|
||||
"PLR0915", # too-many-statements
|
||||
"PLR0916", # too-many-boolean-expressions
|
||||
"PLR1702", # too-many-nested-blocks
|
||||
"PLR1704", # redefined-argument-from-local
|
||||
"PLR1711", # useless-return
|
||||
"C416", # unnecessary-comprehension
|
||||
"PLR1733", # unnecessary-dict-index-lookup
|
||||
"PLR1736", # unnecessary-list-index-lookup
|
||||
|
||||
# ruff reports this rule is unstable
|
||||
#"PLR6301", # no-self-use
|
||||
|
||||
"PLW0108", # unnecessary-lambda
|
||||
"PLW0120", # useless-else-on-loop
|
||||
"PLW0127", # self-assigning-variable
|
||||
"PLW0129", # assert-on-string-literal
|
||||
"B033", # duplicate-value
|
||||
"PLW0131", # named-expr-without-context
|
||||
"PLW0245", # super-without-brackets
|
||||
"PLW0406", # import-self
|
||||
"PLW0602", # global-variable-not-assigned
|
||||
"PLW0603", # global-statement
|
||||
"PLW0604", # global-at-module-level
|
||||
|
||||
# fails on the try: import typing used by libraries
|
||||
#"F401", # unused-import
|
||||
|
||||
"F841", # unused-variable
|
||||
"E722", # bare-except
|
||||
"PLW0711", # binary-op-exception
|
||||
"PLW1501", # bad-open-mode
|
||||
"PLW1508", # invalid-envvar-default
|
||||
"PLW1509", # subprocess-popen-preexec-fn
|
||||
"PLW2101", # useless-with-lock
|
||||
"PLW3301", # nested-min-max
|
||||
]
|
||||
|
||||
ignore = [
|
||||
"PLR2004", # magic-value-comparison
|
||||
"UP030", # format literals
|
||||
"PLW1514", # unspecified-encoding
|
||||
"PLR0913", # too-many-arguments
|
||||
"PLR0915", # too-many-statements
|
||||
"PLR0917", # too-many-positional-arguments
|
||||
"PLR0904", # too-many-public-methods
|
||||
"PLR0912", # too-many-branches
|
||||
"PLR0916", # too-many-boolean-expressions
|
||||
"PLR6301", # could-be-static no-self-use
|
||||
"PLC0415", # import outside toplevel
|
||||
"PLC2701", # private import
|
||||
"PLW2901", # loop var overwrite
|
||||
"PLW1641", # obj not implement hash function
|
||||
"PLR0914", # too many locals
|
||||
]
|
||||
|
||||
[format]
|
||||
line-ending = "lf"
|
||||
|
|
@ -12,10 +12,10 @@
|
|||
# pylint:disable=invalid-name, no-member, wrong-import-position, undefined-variable, no-self-use, cell-var-from-loop, too-many-public-methods, fixme, import-outside-toplevel, unused-argument, too-few-public-methods
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import MAXYEAR, MINYEAR
|
||||
|
||||
# CPython standard implementation
|
||||
from datetime import date as cpython_date
|
||||
from datetime import MINYEAR, MAXYEAR
|
||||
|
||||
# CircuitPython subset implementation
|
||||
sys.path.append("..")
|
||||
|
|
@ -130,9 +130,7 @@ class TestDate(unittest.TestCase):
|
|||
|
||||
# It worked or it didn't. If it didn't, assume it's reason #2, and
|
||||
# let the test pass if they're within half a second of each other.
|
||||
self.assertTrue(
|
||||
today == todayagain or abs(todayagain - today) < timedelta(seconds=0.5)
|
||||
)
|
||||
self.assertTrue(today == todayagain or abs(todayagain - today) < timedelta(seconds=0.5))
|
||||
|
||||
def test_weekday(self):
|
||||
for i in range(7):
|
||||
|
|
@ -155,9 +153,7 @@ class TestDate(unittest.TestCase):
|
|||
cpython_date(1956, 1, 2 + i).isoweekday(),
|
||||
)
|
||||
|
||||
@unittest.skip(
|
||||
"Skip for CircuitPython - isocalendar() not implemented for date objects."
|
||||
)
|
||||
@unittest.skip("Skip for CircuitPython - isocalendar() not implemented for date objects.")
|
||||
def test_isocalendar(self):
|
||||
# Check examples from
|
||||
# http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
|
||||
|
|
@ -187,9 +183,7 @@ class TestDate(unittest.TestCase):
|
|||
t = cpy_date(2002, 3, 2)
|
||||
self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002")
|
||||
|
||||
@unittest.skip(
|
||||
"Skip for CircuitPython - strftime() not implemented for date objects."
|
||||
)
|
||||
@unittest.skip("Skip for CircuitPython - strftime() not implemented for date objects.")
|
||||
def test_strftime(self):
|
||||
t = cpy_date(2005, 3, 2)
|
||||
self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05")
|
||||
|
|
@ -252,9 +246,7 @@ class TestDate(unittest.TestCase):
|
|||
self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
|
||||
self.assertEqual(b.__format__(fmt), 'B')"""
|
||||
|
||||
@unittest.skip(
|
||||
"Skip for CircuitPython - min/max/resolution not implemented for date objects."
|
||||
)
|
||||
@unittest.skip("Skip for CircuitPython - min/max/resolution not implemented for date objects.")
|
||||
def test_resolution_info(self):
|
||||
# XXX: Should min and max respect subclassing?
|
||||
if issubclass(cpy_date, datetime):
|
||||
|
|
@ -405,9 +397,7 @@ class TestDate(unittest.TestCase):
|
|||
self.assertEqual(our < their, True)
|
||||
self.assertEqual(their < our, False)
|
||||
|
||||
@unittest.skip(
|
||||
"Skip for CircuitPython - min/max date attributes not implemented yet."
|
||||
)
|
||||
@unittest.skip("Skip for CircuitPython - min/max date attributes not implemented yet.")
|
||||
def test_bool(self):
|
||||
# All dates are considered true.
|
||||
self.assertTrue(cpy_date.min)
|
||||
|
|
|
|||
|
|
@ -14,20 +14,17 @@ import sys
|
|||
|
||||
# CircuitPython subset implementation
|
||||
sys.path.append("..")
|
||||
from adafruit_datetime import datetime as cpy_datetime
|
||||
from adafruit_datetime import timedelta
|
||||
from adafruit_datetime import tzinfo
|
||||
from adafruit_datetime import date
|
||||
from adafruit_datetime import time
|
||||
from adafruit_datetime import timezone
|
||||
|
||||
import unittest
|
||||
from test import support
|
||||
from test_date import TestDate
|
||||
from datetime import MAXYEAR, MINYEAR
|
||||
|
||||
# CPython standard implementation
|
||||
from datetime import datetime as cpython_datetime
|
||||
from datetime import MINYEAR, MAXYEAR
|
||||
from test import support
|
||||
|
||||
from test_date import TestDate
|
||||
|
||||
from adafruit_datetime import date, time, timedelta, timezone, tzinfo
|
||||
from adafruit_datetime import datetime as cpy_datetime
|
||||
|
||||
|
||||
# TZinfo test
|
||||
|
|
@ -158,12 +155,8 @@ class TestDateTime(TestDate):
|
|||
self.assertEqual(t.isoformat(timespec="hours"), "0001-02-03T04")
|
||||
self.assertEqual(t.isoformat(timespec="minutes"), "0001-02-03T04:05")
|
||||
self.assertEqual(t.isoformat(timespec="seconds"), "0001-02-03T04:05:01")
|
||||
self.assertEqual(
|
||||
t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.000"
|
||||
)
|
||||
self.assertEqual(
|
||||
t.isoformat(timespec="microseconds"), "0001-02-03T04:05:01.000123"
|
||||
)
|
||||
self.assertEqual(t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.000")
|
||||
self.assertEqual(t.isoformat(timespec="microseconds"), "0001-02-03T04:05:01.000123")
|
||||
self.assertEqual(t.isoformat(timespec="auto"), "0001-02-03T04:05:01.000123")
|
||||
self.assertEqual(t.isoformat(sep=" ", timespec="minutes"), "0001-02-03 04:05")
|
||||
self.assertRaises(ValueError, t.isoformat, timespec="foo")
|
||||
|
|
@ -173,23 +166,15 @@ class TestDateTime(TestDate):
|
|||
self.assertEqual(str(t), "0001-02-03 04:05:01.000123")
|
||||
|
||||
t = self.theclass(1, 2, 3, 4, 5, 1, 999500, tzinfo=timezone.utc)
|
||||
self.assertEqual(
|
||||
t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.999+00:00"
|
||||
)
|
||||
self.assertEqual(t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.999+00:00")
|
||||
|
||||
t = self.theclass(1, 2, 3, 4, 5, 1, 999500)
|
||||
self.assertEqual(
|
||||
t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.999"
|
||||
)
|
||||
self.assertEqual(t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.999")
|
||||
|
||||
t = self.theclass(1, 2, 3, 4, 5, 1)
|
||||
self.assertEqual(t.isoformat(timespec="auto"), "0001-02-03T04:05:01")
|
||||
self.assertEqual(
|
||||
t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.000"
|
||||
)
|
||||
self.assertEqual(
|
||||
t.isoformat(timespec="microseconds"), "0001-02-03T04:05:01.000000"
|
||||
)
|
||||
self.assertEqual(t.isoformat(timespec="milliseconds"), "0001-02-03T04:05:01.000")
|
||||
self.assertEqual(t.isoformat(timespec="microseconds"), "0001-02-03T04:05:01.000000")
|
||||
|
||||
t = self.theclass(2, 3, 2)
|
||||
self.assertEqual(t.isoformat(), "0002-03-02T00:00:00")
|
||||
|
|
@ -284,9 +269,7 @@ class TestDateTime(TestDate):
|
|||
|
||||
# So test a case where that difference doesn't matter.
|
||||
t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
|
||||
self.assertEqual(
|
||||
t.ctime(), cpython_time.ctime(cpython_time.mktime(t.timetuple()))
|
||||
)
|
||||
self.assertEqual(t.ctime(), cpython_time.ctime(cpython_time.mktime(t.timetuple())))
|
||||
|
||||
def test_tz_independent_comparing(self):
|
||||
dt1 = self.theclass(2002, 3, 1, 9, 0, 0)
|
||||
|
|
@ -435,16 +418,12 @@ class TestDateTime(TestDate):
|
|||
a + (week + day + hour + millisec),
|
||||
self.theclass(2002, 3, 10, 18, 6, 0, 1000),
|
||||
)
|
||||
self.assertEqual(
|
||||
a + (week + day + hour + millisec), (((a + week) + day) + hour) + millisec
|
||||
)
|
||||
self.assertEqual(a + (week + day + hour + millisec), (((a + week) + day) + hour) + millisec)
|
||||
self.assertEqual(
|
||||
a - (week + day + hour + millisec),
|
||||
self.theclass(2002, 2, 22, 16, 5, 59, 999000),
|
||||
)
|
||||
self.assertEqual(
|
||||
a - (week + day + hour + millisec), (((a - week) - day) - hour) - millisec
|
||||
)
|
||||
self.assertEqual(a - (week + day + hour + millisec), (((a - week) - day) - hour) - millisec)
|
||||
# Add/sub ints or floats should be illegal
|
||||
for i in 1, 1.0:
|
||||
self.assertRaises(TypeError, lambda: a + i)
|
||||
|
|
@ -532,12 +511,8 @@ class TestDateTime(TestDate):
|
|||
# Missing hour
|
||||
t0 = self.theclass(2012, 3, 11, 2, 30)
|
||||
t1 = t0.replace(fold=1)
|
||||
self.assertEqual(
|
||||
self.theclass.fromtimestamp(t1.timestamp()), t0 - timedelta(hours=1)
|
||||
)
|
||||
self.assertEqual(
|
||||
self.theclass.fromtimestamp(t0.timestamp()), t1 + timedelta(hours=1)
|
||||
)
|
||||
self.assertEqual(self.theclass.fromtimestamp(t1.timestamp()), t0 - timedelta(hours=1))
|
||||
self.assertEqual(self.theclass.fromtimestamp(t0.timestamp()), t1 + timedelta(hours=1))
|
||||
# Ambiguous hour defaults to DST
|
||||
t = self.theclass(2012, 11, 4, 1, 30)
|
||||
self.assertEqual(self.theclass.fromtimestamp(t.timestamp()), t)
|
||||
|
|
@ -556,9 +531,7 @@ class TestDateTime(TestDate):
|
|||
self.assertEqual(t.timestamp(), 0.0)
|
||||
t = self.theclass(1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone.utc)
|
||||
self.assertEqual(t.timestamp(), 3600 + 2 * 60 + 3 + 4 * 1e-6)
|
||||
t = self.theclass(
|
||||
1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone(timedelta(hours=-5), "EST")
|
||||
)
|
||||
t = self.theclass(1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone(timedelta(hours=-5), "EST"))
|
||||
self.assertEqual(t.timestamp(), 18000 + 3600 + 2 * 60 + 3 + 4 * 1e-6)
|
||||
|
||||
@unittest.skip("Not implemented - gmtime")
|
||||
|
|
@ -609,9 +582,7 @@ class TestDateTime(TestDate):
|
|||
min_ts = min_dt.timestamp()
|
||||
try:
|
||||
# date 0001-01-01 00:00:00+00:00: timestamp=-62135596800
|
||||
self.assertEqual(
|
||||
self.theclass.fromtimestamp(min_ts, tz=timezone.utc), min_dt
|
||||
)
|
||||
self.assertEqual(self.theclass.fromtimestamp(min_ts, tz=timezone.utc), min_dt)
|
||||
except (OverflowError, OSError) as exc:
|
||||
# the date 0001-01-01 doesn't fit into 32-bit time_t,
|
||||
# or platform doesn't support such very old date
|
||||
|
|
@ -718,7 +689,7 @@ class TestDateTime(TestDate):
|
|||
sign = "+"
|
||||
seconds = tzseconds
|
||||
hours, minutes = divmod(seconds // 60, 60)
|
||||
dtstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname)
|
||||
dtstr = f"{sign}{hours:02d}{minutes:02d} {tzname}"
|
||||
dt = strptime(dtstr, "%z %Z")
|
||||
self.assertEqual(dt.utcoffset(), timedelta(seconds=tzseconds))
|
||||
self.assertEqual(dt.tzname(), tzname)
|
||||
|
|
@ -766,9 +737,7 @@ class TestDateTime(TestDate):
|
|||
]
|
||||
for reason, string, format, target in inputs:
|
||||
reason = "test single digit " + reason
|
||||
with self.subTest(
|
||||
reason=reason, string=string, format=format, target=target
|
||||
):
|
||||
with self.subTest(reason=reason, string=string, format=format, target=target):
|
||||
newdate = strptime(string, format)
|
||||
self.assertEqual(newdate, target, msg=reason)
|
||||
|
||||
|
|
@ -805,9 +774,7 @@ class TestDateTime(TestDate):
|
|||
def test_more_strftime(self):
|
||||
# This tests fields beyond those tested by the TestDate.test_strftime.
|
||||
t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
|
||||
self.assertEqual(
|
||||
t.strftime("%m %d %y %f %S %M %H %j"), "12 31 04 000047 33 22 06 366"
|
||||
)
|
||||
self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"), "12 31 04 000047 33 22 06 366")
|
||||
for (s, us), z in [
|
||||
((33, 123), "33.000123"),
|
||||
((33, 0), "33"),
|
||||
|
|
@ -996,9 +963,7 @@ class TestDateTime(TestDate):
|
|||
for constr_name, constr_args, expected in test_cases:
|
||||
for base_obj in (DateTimeSubclass, base_d):
|
||||
# Test both the classmethod and method
|
||||
with self.subTest(
|
||||
base_obj_type=type(base_obj), constr_name=constr_name
|
||||
):
|
||||
with self.subTest(base_obj_type=type(base_obj), constr_name=constr_name):
|
||||
constructor = getattr(base_obj, constr_name)
|
||||
|
||||
dt = constructor(*constr_args)
|
||||
|
|
|
|||
|
|
@ -14,12 +14,12 @@
|
|||
import sys
|
||||
|
||||
sys.path.append("..")
|
||||
from adafruit_datetime import time as cpy_time
|
||||
import unittest
|
||||
|
||||
# CPython standard implementation
|
||||
from datetime import time as cpython_time
|
||||
import unittest
|
||||
|
||||
from adafruit_datetime import time as cpy_time
|
||||
|
||||
# An arbitrary collection of objects of non-datetime types, for testing
|
||||
# mixed-type comparisons.
|
||||
|
|
@ -274,12 +274,8 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
|
|||
def test_repr(self):
|
||||
name = "datetime." + self.theclass.__name__
|
||||
self.assertEqual(repr(self.theclass(1, 2, 3, 4)), "%s(1, 2, 3, 4)" % name)
|
||||
self.assertEqual(
|
||||
repr(self.theclass(10, 2, 3, 4000)), "%s(10, 2, 3, 4000)" % name
|
||||
)
|
||||
self.assertEqual(
|
||||
repr(self.theclass(0, 2, 3, 400000)), "%s(0, 2, 3, 400000)" % name
|
||||
)
|
||||
self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), "%s(10, 2, 3, 4000)" % name)
|
||||
self.assertEqual(repr(self.theclass(0, 2, 3, 400000)), "%s(0, 2, 3, 400000)" % name)
|
||||
self.assertEqual(repr(self.theclass(12, 2, 3, 0)), "%s(12, 2, 3)" % name)
|
||||
self.assertEqual(repr(self.theclass(23, 15, 0, 0)), "%s(23, 15)" % name)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue