Skip to content

Commit 54c331c

Browse files
committed
Move from pytz to zoneinfo
Since Python 3.9 zoneinfo is available and datetime also has a timezone module attribute which can be used. Also refactor the utcnow/fromutctimestamp usage to according to this excellent blogpost. https://blog.ganssle.io/articles/2019/11/utcnow.html
1 parent 74531f6 commit 54c331c

File tree

14 files changed

+675
-43
lines changed

14 files changed

+675
-43
lines changed

devel/management/commands/pgp_import.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@
88
"""
99

1010
from collections import OrderedDict
11-
from datetime import datetime
11+
from datetime import datetime, timezone
1212
import logging
13-
from pytz import utc
1413
import subprocess
1514

1615
from django.core.management.base import BaseCommand, CommandError
@@ -50,14 +49,14 @@ def get_date(epoch_string):
5049
'''Convert a epoch string into a python 'date' object (not datetime).'''
5150
if not epoch_string:
5251
return None
53-
return datetime.utcfromtimestamp(int(epoch_string)).date()
52+
return datetime.fromtimestamp(int(epoch_string), tz=timezone.utc).date()
5453

5554

5655
def get_datetime(epoch_string):
5756
'''Convert a epoch string into a python 'datetime' object.'''
5857
if not epoch_string:
5958
return None
60-
return datetime.utcfromtimestamp(int(epoch_string)).replace(tzinfo=utc)
59+
return datetime.fromtimestamp(int(epoch_string), tz=timezone.utc)
6160

6261

6362
def call_gpg(keyring, *args):

devel/management/commands/reporead.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@
2121
import re
2222
import xtarfile as tarfile
2323
import logging
24-
from datetime import datetime
25-
from pytz import utc
24+
from datetime import datetime, timezone
2625

2726
from django.core.management.base import BaseCommand, CommandError
2827
from django.db import connections, router, transaction
@@ -120,8 +119,7 @@ def populate(self, values):
120119
self.ver, self.rel, self.epoch = parse_version(v[0])
121120
elif k == 'builddate':
122121
try:
123-
builddate = datetime.utcfromtimestamp(int(v[0]))
124-
self.builddate = builddate.replace(tzinfo=utc)
122+
self.builddate = datetime.fromtimestamp(int(v[0]), tz=timezone.utc)
125123
except ValueError:
126124
logger.warning(
127125
'Package %s had unparsable build date %s',

devel/migrations/0009_alter_userprofile_time_zone_alter_userprofile_yob.py

Lines changed: 647 additions & 0 deletions
Large diffs are not rendered by default.

devel/models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
import pytz
2+
import zoneinfo
33

44
from django.urls import reverse
55
from django.db import models
@@ -23,7 +23,7 @@ class UserProfile(models.Model):
2323
help_text="When enabled, send user 'flag out-of-date' notifications")
2424
time_zone = models.CharField(
2525
max_length=100,
26-
choices=make_choice(pytz.common_timezones),
26+
choices=make_choice(sorted(zoneinfo.available_timezones())), # sort as available_timezones output varies
2727
default="UTC",
2828
help_text="Used for developer clock page")
2929
alias = models.CharField(

devel/reports.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from collections import defaultdict
2-
from datetime import timedelta
2+
from datetime import timedelta, timezone
33

4-
import pytz
54
from django.db.models import F
65
from django.template.defaultfilters import filesizeformat
76
from django.db import connection
@@ -171,7 +170,7 @@ def signature_time(packages):
171170
'arch', 'repo', 'packager').filter(signature_bytes__isnull=False)
172171
for package in packages:
173172
sig = package.signature
174-
sig_date = sig.creation_time.replace(tzinfo=pytz.utc)
173+
sig_date = sig.creation_time.replace(tzinfo=timezone.utc)
175174
package.sig_date = sig_date.date()
176175
if sig_date > package.build_date + cutoff:
177176
filtered.append(package)

feeds.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
from datetime import datetime, time
2-
from pytz import utc
1+
from datetime import datetime, timezone, time
32

43
from django.core.exceptions import ObjectDoesNotExist
54
from django.contrib.admin.models import ADDITION, DELETION
@@ -363,7 +362,7 @@ def item_description(self, item):
363362
return item.info_html()
364363

365364
def item_pubdate(self, item):
366-
return datetime.combine(item.release_date, time()).replace(tzinfo=utc)
365+
return datetime.combine(item.release_date, time()).replace(tzinfo=timezone.utc)
367366

368367
def item_updateddate(self, item):
369368
return item.last_modified
@@ -416,7 +415,7 @@ def item_description(self, item):
416415
return item.summary
417416

418417
def item_pubdate(self, item):
419-
return datetime.combine(item.publishdate, time()).replace(tzinfo=utc)
418+
return datetime.combine(item.publishdate, time()).replace(tzinfo=timezone.utc)
420419

421420
def item_updateddate(self, item):
422421
return item.publishdate

main/log.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
# Derived from Django snippets: http://djangosnippets.org/snippets/2242/
22
from collections import OrderedDict
3-
from datetime import datetime, timedelta
3+
from datetime import datetime, timedelta, timezone
44
from hashlib import md5
55
import traceback
6-
from pytz import utc
76

87

98
class LimitedSizeDict(OrderedDict):
@@ -60,7 +59,7 @@ def filter(self, record):
6059
duplicate = (cache.get(cache_key) == 1)
6160
cache.set(cache_key, 1, self.rate)
6261
else:
63-
now = datetime.utcnow().replace(tzinfo=utc)
62+
now = datetime.now(timezone.utc)
6463
min_date = now - timedelta(seconds=self.rate)
6564
duplicate = (key in self.errors and self.errors[key] >= min_date)
6665
self.errors[key] = now

main/models.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from itertools import groupby
22
from pgpdump import BinaryData
3-
from pytz import utc
4-
from datetime import datetime
3+
from datetime import datetime, timezone
54

65
from django.db import models
76
from django.db.models import Q
@@ -141,7 +140,7 @@ def updated_mins_ago(self):
141140
# package was actually pushed to any repo. We don't have that
142141
# easily available without adding more fields and scripts.
143142
# See: https://github.com/archlinux/archweb/pull/323
144-
now = datetime.utcnow().replace(tzinfo=utc)
143+
now = datetime.now(timezone.utc)
145144
return int((now - self.last_update).total_seconds()) // 60
146145

147146
@property

mirrors/management/commands/mirrorcheck.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,10 @@
1010
"""
1111

1212
from collections import deque
13-
from datetime import datetime, timedelta
13+
from datetime import datetime, timedelta, timezone
1414
from http.client import HTTPException
1515
import logging
1616
import os
17-
from pytz import utc
1817
import re
1918
import socket
2019
import ssl
@@ -97,8 +96,7 @@ def wrapper(host, port, family=0, socktype=0, proto=0, flags=0):
9796
def parse_lastsync(log, data):
9897
'''lastsync file should be an epoch value created by us.'''
9998
try:
100-
parsed_time = datetime.utcfromtimestamp(int(data))
101-
log.last_sync = parsed_time.replace(tzinfo=utc)
99+
log.last_sync = datetime.fromtimestamp(int(data), tz=timezone.utc)
102100
except (TypeError, ValueError):
103101
# it is bad news to try logging the lastsync value;
104102
# sometimes we get a crazy-encoded web page.

planet/management/commands/update_planet.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
import logging
1212
import time
1313

14-
from datetime import datetime
15-
from pytz import utc
14+
from datetime import datetime, timezone
1615

1716
import bleach
1817
import feedparser
@@ -104,7 +103,7 @@ def parse_entry(self, entry, feed_instance, latest):
104103
logger.error("feed: '%s' has no published or updated date", url)
105104
return
106105

107-
published = datetime.fromtimestamp(time.mktime(published_parsed)).replace(tzinfo=utc)
106+
published = datetime.fromtimestamp(time.mktime(published_parsed)).replace(tzinfo=timezone.utc)
108107

109108
if latest and latest.publishdate >= published:
110109
logger.debug("feed: '%s' has no more new entries", url)

0 commit comments

Comments
 (0)