Skip to content

Commit

Permalink
fix DeprecationWarning with datetime.utcnow() (#86)
Browse files Browse the repository at this point in the history
This is not the same as
#71, but it
originates at the same point. When I updated pytz to 2023.3.post1, I
started getting:
```
E       DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
```
This fixes it.

---------

Co-authored-by: Samuel Colvin <[email protected]>
  • Loading branch information
MeggyCal and samuelcolvin authored Nov 14, 2023
1 parent d7d5563 commit 4e4fb62
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ jobs:

- uses: actions/setup-python@v4
with:
python-version: '3.10'
python-version: '3.11'

- run: pip install -r requirements/linting.txt

Expand Down
8 changes: 7 additions & 1 deletion dirty_equals/_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,13 @@ def _get_now(self) -> datetime:
if self.tz is None:
return datetime.now()
else:
return datetime.utcnow().replace(tzinfo=timezone.utc).astimezone(self.tz)
try:
from datetime import UTC

utc_now = datetime.now(UTC).replace(tzinfo=timezone.utc)
except ImportError:
utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
return utc_now.astimezone(self.tz)

def prepare(self, other: Any) -> datetime:
# update approx for every comparing, to check if other value is dirty equal
Expand Down
9 changes: 7 additions & 2 deletions tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,13 @@ def test_repr():


def test_is_now_tz():
now_ny = datetime.utcnow().replace(tzinfo=timezone.utc).astimezone(pytz.timezone('America/New_York'))
try:
from datetime import UTC

utc_now = datetime.now(UTC).replace(tzinfo=timezone.utc)
except ImportError:
utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
now_ny = utc_now.astimezone(pytz.timezone('America/New_York'))
assert now_ny == IsNow(tz='America/New_York')
# depends on the time of year and DST
assert now_ny == IsNow(tz=timezone(timedelta(hours=-5))) | IsNow(tz=timezone(timedelta(hours=-4)))
Expand All @@ -111,7 +117,6 @@ def test_is_now_tz():
assert now.isoformat() == IsNow(iso_string=True)
assert now.isoformat() != IsNow

utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
assert utc_now == IsNow(tz=timezone.utc)


Expand Down

0 comments on commit 4e4fb62

Please sign in to comment.