From 0f8b8fd08ab026c8c5bfa6875841cf7c4884efdb Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Sun, 4 Aug 2024 07:15:56 -0400 Subject: [PATCH] fix ruff DTZ003 (closes #3791) --- pyproject.toml | 1 - src/pymatgen/alchemy/materials.py | 8 ++++---- src/pymatgen/analysis/ewald.py | 6 +++--- src/pymatgen/entries/entry_tools.py | 8 ++++---- src/pymatgen/io/res.py | 7 +++---- src/pymatgen/io/vasp/outputs.py | 4 ++-- src/pymatgen/util/provenance.py | 4 ++-- tasks.py | 6 +++--- 8 files changed, 21 insertions(+), 23 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 1c54e9b36e5..c9ffd4df0a8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -205,7 +205,6 @@ ignore = [ "D105", # Missing docstring in magic method "D205", # 1 blank line required between summary line and description "D212", # Multi-line docstring summary should start at the first line - "DTZ003", # TODO: fix this (issue #3791) "FBT001", # Boolean-typed positional argument in function definition "FBT002", # Boolean default positional argument in function "PD901", # pandas-df-variable-name diff --git a/src/pymatgen/alchemy/materials.py b/src/pymatgen/alchemy/materials.py index 2fa8b754721..848352ad8c5 100644 --- a/src/pymatgen/alchemy/materials.py +++ b/src/pymatgen/alchemy/materials.py @@ -5,9 +5,9 @@ from __future__ import annotations -import datetime import json import re +from datetime import datetime, timezone from typing import TYPE_CHECKING from warnings import warn @@ -302,7 +302,7 @@ def from_cif_str( source = "uploaded cif" source_info = { "source": source, - "datetime": str(datetime.datetime.now(tz=datetime.timezone.utc)), + "datetime": str(datetime.now(tz=timezone.utc)), "original_file": raw_str, "cif_data": cif_dict[cif_keys[0]], } @@ -330,7 +330,7 @@ def from_poscar_str( struct = poscar.structure source_info = { "source": "POSCAR", - "datetime": str(datetime.datetime.now(tz=datetime.timezone.utc)), + "datetime": str(datetime.now(tz=timezone.utc)), "original_file": raw_str, } return cls(struct, transformations, history=[source_info]) @@ -341,7 +341,7 @@ def as_dict(self) -> dict[str, Any]: dct["@module"] = type(self).__module__ dct["@class"] = type(self).__name__ dct["history"] = jsanitize(self.history) - dct["last_modified"] = str(datetime.datetime.now(datetime.timezone.utc)) + dct["last_modified"] = str(datetime.now(timezone.utc)) dct["other_parameters"] = jsanitize(self.other_parameters) return dct diff --git a/src/pymatgen/analysis/ewald.py b/src/pymatgen/analysis/ewald.py index e37d6a4c793..4cf0964ef90 100644 --- a/src/pymatgen/analysis/ewald.py +++ b/src/pymatgen/analysis/ewald.py @@ -5,7 +5,7 @@ import bisect import math from copy import copy, deepcopy -from datetime import datetime +from datetime import datetime, timezone from typing import TYPE_CHECKING from warnings import warn @@ -535,7 +535,7 @@ def __init__(self, matrix, m_list, num_to_return=1, algo=ALGO_FAST): # sets this to true it breaks the recursion and stops the search. self._finished = False - self._start_time = datetime.utcnow() + self._start_time = datetime.now(tz=timezone.utc) self.minimize_matrix() @@ -605,7 +605,7 @@ def best_case(self, matrix, m_list, indices_left): interaction_correction = np.sum(step3) if self._algo == self.ALGO_TIME_LIMIT: - elapsed_time = datetime.utcnow() - self._start_time + elapsed_time = datetime.now(tz=timezone.utc) - self._start_time speedup_parameter = elapsed_time.total_seconds() / 1800 avg_int = np.sum(interaction_matrix, axis=None) avg_frac = np.mean(np.outer(1 - fractions, 1 - fractions)) diff --git a/src/pymatgen/entries/entry_tools.py b/src/pymatgen/entries/entry_tools.py index 6fe98612ca5..71581cc22e9 100644 --- a/src/pymatgen/entries/entry_tools.py +++ b/src/pymatgen/entries/entry_tools.py @@ -6,13 +6,13 @@ import collections import csv -import datetime import itertools import json import logging import multiprocessing as mp import re from collections import defaultdict +from datetime import datetime, timezone from typing import TYPE_CHECKING from monty.json import MontyDecoder, MontyEncoder, MSONable @@ -112,7 +112,7 @@ def group_entries_by_structure( """ if comparator is None: comparator = SpeciesComparator() - start = datetime.datetime.now(tz=datetime.timezone.utc) + start = datetime.now(tz=timezone.utc) logger.info(f"Started at {start}") entries_host = [(entry, _get_host(entry.structure, species_to_remove)) for entry in entries] if ncpus: @@ -161,8 +161,8 @@ def group_entries_by_structure( entry_groups = [] for g in groups: entry_groups.append(json.loads(g, cls=MontyDecoder)) - logging.info(f"Finished at {datetime.datetime.now(tz=datetime.timezone.utc)}") - logging.info(f"Took {datetime.datetime.now(tz=datetime.timezone.utc) - start}") + logging.info(f"Finished at {datetime.now(tz=timezone.utc)}") + logging.info(f"Took {datetime.now(tz=timezone.utc) - start}") return entry_groups diff --git a/src/pymatgen/io/res.py b/src/pymatgen/io/res.py index d43efbaaf00..e884ee13c98 100644 --- a/src/pymatgen/io/res.py +++ b/src/pymatgen/io/res.py @@ -10,9 +10,9 @@ from __future__ import annotations -import datetime import re from dataclasses import dataclass +from datetime import date, datetime, timezone from typing import TYPE_CHECKING from monty.io import zopen @@ -24,7 +24,6 @@ if TYPE_CHECKING: from collections.abc import Iterator - from datetime import date from pathlib import Path from typing import Any, Callable, Literal @@ -421,9 +420,9 @@ def _parse_date(cls, string: str) -> date: raise ResParseError(f"Could not parse the date from {string=}.") day, month, year, *_ = match.groups() - month_num = datetime.datetime.strptime(month, "%b").replace(tzinfo=datetime.timezone.utc).month + month_num = datetime.strptime(month, "%b").replace(tzinfo=timezone.utc).month - return datetime.date(int(year), month_num, int(day)) + return date(int(year), month_num, int(day)) def _raise_or_none(self, err: ResParseError) -> None: if self.parse_rems != "strict": diff --git a/src/pymatgen/io/vasp/outputs.py b/src/pymatgen/io/vasp/outputs.py index 7aaddb10d61..d44f0f894ba 100644 --- a/src/pymatgen/io/vasp/outputs.py +++ b/src/pymatgen/io/vasp/outputs.py @@ -2,7 +2,6 @@ from __future__ import annotations -import datetime import itertools import logging import math @@ -13,6 +12,7 @@ from collections import defaultdict from collections.abc import Iterable from dataclasses import dataclass +from datetime import datetime, timezone from glob import glob from io import StringIO from pathlib import Path @@ -845,7 +845,7 @@ def get_computed_entry( ComputedStructureEntry/ComputedEntry """ if entry_id is None: - entry_id = f"vasprun-{datetime.datetime.now(tz=datetime.timezone.utc)}" + entry_id = f"vasprun-{datetime.now(tz=timezone.utc)}" param_names = { "is_hubbard", "hubbards", diff --git a/src/pymatgen/util/provenance.py b/src/pymatgen/util/provenance.py index 24193a6bf69..640ab802536 100644 --- a/src/pymatgen/util/provenance.py +++ b/src/pymatgen/util/provenance.py @@ -2,10 +2,10 @@ from __future__ import annotations -import datetime import json import re import sys +from datetime import datetime, timezone from io import StringIO from typing import TYPE_CHECKING, NamedTuple @@ -256,7 +256,7 @@ def __init__( if not all(sys.getsizeof(h) < MAX_HNODE_SIZE for h in history): raise ValueError(f"One or more history nodes exceeds the maximum size limit of {MAX_HNODE_SIZE} bytes") - self.created_at = created_at or datetime.datetime.utcnow() + self.created_at = created_at or datetime.now(tz=timezone.utc) def as_dict(self): """Get MSONable dict.""" diff --git a/tasks.py b/tasks.py index 2ad2ee2ec13..607c5276143 100644 --- a/tasks.py +++ b/tasks.py @@ -9,12 +9,12 @@ from __future__ import annotations -import datetime import json import os import re import subprocess import webbrowser +from datetime import datetime, timezone from typing import TYPE_CHECKING import requests @@ -150,7 +150,7 @@ def update_changelog(ctx: Context, version: str | None = None, dry_run: bool = F dry_run (bool, optional): If True, the function will only print the changes without updating the actual change log file. Defaults to False. """ - version = version or f"{datetime.datetime.now(tz=datetime.timezone.utc):%Y.%-m.%-d}" + version = version or f"{datetime.now(tz=timezone.utc):%Y.%-m.%-d}" output = subprocess.check_output(["git", "log", "--pretty=format:%s", f"v{__version__}..HEAD"]) lines = [] ignored_commits = [] @@ -197,7 +197,7 @@ def release(ctx: Context, version: str | None = None, nodoc: bool = False) -> No version (str, optional): The version to release. nodoc (bool, optional): Whether to skip documentation generation. """ - version = version or f"{datetime.datetime.now(tz=datetime.timezone.utc):%Y.%-m.%-d}" + version = version or f"{datetime.now(tz=timezone.utc):%Y.%-m.%-d}" ctx.run("rm -r dist build pymatgen.egg-info", warn=True) set_ver(ctx, version) if not nodoc: