Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
python: Consistently use from…import for datetime.
Anders Kaseorg8a7916f21aac
diff --git a/analytics/models.py b/analytics/models.pyindex 4ec03edf647..2ebe57338ad 100644--- a/analytics/models.py+++ b/analytics/models.py@@ -1,7 +1,7 @@# https://github.com/typeddjango/django-stubs/issues/1698# mypy: disable-error-code="explicit-override"-import datetime+from datetime import datetimefrom django.db import modelsfrom django.db.models import Q, UniqueConstraint@@ -27,7 +27,7 @@ class FillState(models.Model):# The earliest/starting end_time in FillState# We assume there is at least one realm-def installation_epoch() -> datetime.datetime:+def installation_epoch() -> datetime:earliest_realm_creation = Realm.objects.aggregate(models.Min("date_created"))["date_created__min"]diff --git a/confirmation/models.py b/confirmation/models.pyindex 33da8f69fab..c63607ba219 100644--- a/confirmation/models.py+++ b/confirmation/models.py@@ -1,9 +1,9 @@# Copyright: (c) 2008, Jarek Zgoda <[email protected]>__revision__ = "$Id: models.py 28 2009-10-22 15:03:02Z jarek.zgoda $"-import datetimeimport secretsfrom base64 import b32encode+from datetime import timedeltafrom typing import List, Mapping, Optional, Unionfrom urllib.parse import urljoin@@ -136,11 +136,9 @@ def create_confirmation_link(expiry_date = Noneelse:assert validity_in_minutes is not None- expiry_date = current_time + datetime.timedelta(minutes=validity_in_minutes)+ expiry_date = current_time + timedelta(minutes=validity_in_minutes)else:- expiry_date = current_time + datetime.timedelta(- days=_properties[confirmation_type].validity_in_days- )+ expiry_date = current_time + timedelta(days=_properties[confirmation_type].validity_in_days)Confirmation.objects.create(content_object=obj,diff --git a/corporate/tests/test_remote_billing.py b/corporate/tests/test_remote_billing.pyindex 8886c3057c0..8bb37ddef87 100644--- a/corporate/tests/test_remote_billing.py+++ b/corporate/tests/test_remote_billing.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom typing import TYPE_CHECKING, Optionalfrom unittest import mock@@ -223,7 +223,7 @@ class RemoteBillingAuthenticationTest(BouncerTestCase):# Go to the URL we're redirected to after authentication and make sure# we're granted access.with time_machine.travel(- now + datetime.timedelta(seconds=1),+ now + timedelta(seconds=1),tick=False,):result = self.client_get(final_url, subdomain="selfhosting")@@ -233,7 +233,7 @@ class RemoteBillingAuthenticationTest(BouncerTestCase):# Now go there again, simulating doing this after the session has expired.# We should be denied access and redirected to re-auth.with time_machine.travel(- now + datetime.timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 1),+ now + timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 1),tick=False,):result = self.client_get(final_url, subdomain="selfhosting")@@ -297,7 +297,7 @@ class RemoteBillingAuthenticationTest(BouncerTestCase):# Try the case where the identity dict is simultaneously expired.with time_machine.travel(- now + datetime.timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 30),+ now + timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 30),tick=False,):with self.assertLogs("django.request", "ERROR") as m, self.assertRaises(AssertionError):@@ -512,7 +512,7 @@ class LegacyServerLoginTest(BouncerTestCase):# Now we can simulate an expired identity dict in the session.with time_machine.travel(- now + datetime.timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 30),+ now + timedelta(seconds=REMOTE_BILLING_SESSION_VALIDITY_SECONDS + 30),tick=False,):result = self.client_get(f"/server/{self.uuid}/upgrade/", subdomain="selfhosting")diff --git a/corporate/tests/test_remote_counts.py b/corporate/tests/test_remote_counts.pyindex 346a0025a48..97156d58a49 100644--- a/corporate/tests/test_remote_counts.py+++ b/corporate/tests/test_remote_counts.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltaimport time_machinefrom django.utils.timezone import now as timezone_now@@ -29,7 +29,7 @@ class RemoteCountTest(ZulipTestCase):# inconsistent behavior on the boundaries. E.g. does an entry with# end_time=now - 30 days belong to the "last 30 days" interval or the 30 days before that?# Using now_offset avoids this ambiguity.- now_offset = now + datetime.timedelta(hours=1)+ now_offset = now + timedelta(hours=1)# First try with absolutely no analytics data.with self.assertRaises(MissingDataError):@@ -44,7 +44,7 @@ class RemoteCountTest(ZulipTestCase):remote_id=1,property="active_users_audit:is_bot:day",value=5,- end_time=now_offset - datetime.timedelta(days=4),+ end_time=now_offset - timedelta(days=4),)# If we're missing any message data (which is the same as message data with 0, because@@ -61,7 +61,7 @@ class RemoteCountTest(ZulipTestCase):remote_id=1 + t,property="messages_sent:message_type:day",value=100,- end_time=now_offset - datetime.timedelta(days=90 + (31 - t)),+ end_time=now_offset - timedelta(days=90 + (31 - t)),)for t in range(1, 31))@@ -74,7 +74,7 @@ class RemoteCountTest(ZulipTestCase):remote_id=31 + t,property="messages_sent:message_type:day",value=20,- end_time=now_offset - datetime.timedelta(days=60 + (31 - t)),+ end_time=now_offset - timedelta(days=60 + (31 - t)),)for t in range(1, 31))@@ -86,7 +86,7 @@ class RemoteCountTest(ZulipTestCase):remote_id=61 + t,property="messages_sent:message_type:day",value=30,- end_time=now_offset - datetime.timedelta(days=30 + (31 - t)),+ end_time=now_offset - timedelta(days=30 + (31 - t)),)for t in range(1, 31))@@ -98,7 +98,7 @@ class RemoteCountTest(ZulipTestCase):remote_id=91 + t,property="messages_sent:message_type:day",value=10,- end_time=now_offset - datetime.timedelta(days=(31 - t)),+ end_time=now_offset - timedelta(days=(31 - t)),)for t in range(1, 31))diff --git a/puppet/zulip_ops/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness b/puppet/zulip_ops/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_livenessindex 93e0384f418..3c3a94ecd94 100755--- a/puppet/zulip_ops/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness+++ b/puppet/zulip_ops/files/nagios_plugins/zulip_zephyr_mirror/check_user_zephyr_mirror_liveness@@ -6,9 +6,9 @@ Nagios plugin to check that our MIT users' Zephyr mirrors are running.It must be run on a machine that is using the live database for theDjango ORM."""-import datetimeimport osimport sys+from datetime import timedeltafrom typing import NoReturn, Optionalsys.path.append("/home/zulip/deployments/current")@@ -47,10 +47,10 @@ def report(too_old_data = ""if all_users is not None:recently_inactive_users = (- all_users.filter(last_visit__lt=now - datetime.timedelta(minutes=10))+ all_users.filter(last_visit__lt=now - timedelta(minutes=10)).distinct("user_profile_id").difference(- all_users.filter(last_visit__lt=now - datetime.timedelta(minutes=60)).distinct(+ all_users.filter(last_visit__lt=now - timedelta(minutes=60)).distinct("user_profile_id"))@@ -83,14 +83,14 @@ all_users = UserActivity.objects.filter(client_id=zephyr_client.id,)new_inactive_users = (- all_users.filter(last_visit__lt=now - datetime.timedelta(minutes=10))+ all_users.filter(last_visit__lt=now - timedelta(minutes=10)).values("user_profile_id").distinct("user_profile_id").count())old_inactive_users = (- all_users.filter(last_visit__lt=now - datetime.timedelta(minutes=60))+ all_users.filter(last_visit__lt=now - timedelta(minutes=60)).values("user_profile_id").distinct("user_profile_id").count()diff --git a/scripts/lib/zulip_tools.py b/scripts/lib/zulip_tools.pyindex 0565a3db19b..f79cd78d027 100755--- a/scripts/lib/zulip_tools.py+++ b/scripts/lib/zulip_tools.py@@ -1,7 +1,6 @@#!/usr/bin/env python3import argparseimport configparser-import datetimeimport functoolsimport hashlibimport json@@ -16,6 +15,7 @@ import subprocessimport sysimport timeimport uuid+from datetime import datetime, timedeltafrom typing import IO, Any, Dict, List, Sequence, Setfrom urllib.parse import SplitResult@@ -186,7 +186,7 @@ def su_to_zulip(save_suid: bool = False) -> None:def make_deploy_path() -> str:- timestamp = datetime.datetime.now().strftime(TIMESTAMP_FORMAT) # noqa: DTZ005+ timestamp = datetime.now().strftime(TIMESTAMP_FORMAT) # noqa: DTZ005return os.path.join(DEPLOYMENTS_DIR, timestamp)@@ -302,9 +302,7 @@ def get_recent_deployments(threshold_days: int) -> Set[str]:# Returns a list of deployments not older than threshold days# including `/root/zulip` directory if it exists.recent = set()- threshold_date = datetime.datetime.now() - datetime.timedelta( # noqa: DTZ005- days=threshold_days- )+ threshold_date = datetime.now() - timedelta(days=threshold_days) # noqa: DTZ005for dir_name in os.listdir(DEPLOYMENTS_DIR):target_dir = os.path.join(DEPLOYMENTS_DIR, dir_name)if not os.path.isdir(target_dir):@@ -314,7 +312,7 @@ def get_recent_deployments(threshold_days: int) -> Set[str]:# Skip things like "lock" that aren't actually a deployment directorycontinuetry:- date = datetime.datetime.strptime(dir_name, TIMESTAMP_FORMAT) # noqa: DTZ007+ date = datetime.strptime(dir_name, TIMESTAMP_FORMAT) # noqa: DTZ007if date >= threshold_date:recent.add(target_dir)except ValueError:@@ -331,7 +329,7 @@ def get_recent_deployments(threshold_days: int) -> Set[str]:def get_threshold_timestamp(threshold_days: int) -> int:# Given number of days, this function returns timestamp corresponding# to the time prior to given number of days.- threshold = datetime.datetime.now() - datetime.timedelta(days=threshold_days) # noqa: DTZ005+ threshold = datetime.now() - timedelta(days=threshold_days) # noqa: DTZ005threshold_timestamp = int(time.mktime(threshold.utctimetuple()))return threshold_timestampdiff --git a/zerver/actions/create_realm.py b/zerver/actions/create_realm.pyindex 02c90bc2d89..377223974d7 100644--- a/zerver/actions/create_realm.py+++ b/zerver/actions/create_realm.py@@ -1,5 +1,5 @@-import datetimeimport logging+from datetime import datetime, timedeltafrom typing import Any, Dict, Optionalfrom django.conf import settings@@ -162,7 +162,7 @@ def do_create_realm(plan_type: Optional[int] = None,org_type: Optional[int] = None,default_language: Optional[str] = None,- date_created: Optional[datetime.datetime] = None,+ date_created: Optional[datetime] = None,is_demo_organization: bool = False,enable_read_receipts: Optional[bool] = None,enable_spectator_access: Optional[bool] = None,@@ -223,8 +223,8 @@ def do_create_realm(with transaction.atomic():realm = Realm(string_id=string_id, name=name, **kwargs)if is_demo_organization:- realm.demo_organization_scheduled_deletion_date = (- realm.date_created + datetime.timedelta(days=settings.DEMO_ORG_DEADLINE_DAYS)+ realm.demo_organization_scheduled_deletion_date = realm.date_created + timedelta(+ days=settings.DEMO_ORG_DEADLINE_DAYS)set_realm_permissions_based_on_org_type(realm)diff --git a/zerver/actions/create_user.py b/zerver/actions/create_user.pyindex 51c4f54898b..9b0adb991ca 100644--- a/zerver/actions/create_user.py+++ b/zerver/actions/create_user.py@@ -1,5 +1,5 @@-import datetimefrom collections import defaultdict+from datetime import timedeltafrom typing import Any, Dict, Iterable, List, Optional, Sequence, Setfrom django.conf import settings@@ -65,7 +65,7 @@ MAX_NUM_ONBOARDING_UNREAD_MESSAGES = 20# feel like Zulip is buggy, but in low-traffic or bursty-traffic# organizations, it's reasonable for the most recent 20 messages to be# several weeks old and still be a good place to start.-ONBOARDING_RECENT_TIMEDELTA = datetime.timedelta(weeks=12)+ONBOARDING_RECENT_TIMEDELTA = timedelta(weeks=12)DEFAULT_HISTORICAL_FLAGS = UserMessage.flags.historical | UserMessage.flags.readdiff --git a/zerver/actions/invites.py b/zerver/actions/invites.pyindex 82fcc480b50..48807c85215 100644--- a/zerver/actions/invites.py+++ b/zerver/actions/invites.py@@ -1,5 +1,5 @@-import datetimeimport logging+from datetime import timedeltafrom typing import Any, Collection, Dict, List, Optional, Sequence, Set, Tuple, Unionfrom django.conf import settings@@ -82,7 +82,7 @@ def estimate_recent_invites(realms: Collection[Realm], *, days: int) -> int:recent_invites = RealmCount.objects.filter(realm__in=realms,property="invites_sent::day",- end_time__gte=timezone_now() - datetime.timedelta(days=days),+ end_time__gte=timezone_now() - timedelta(days=days),).aggregate(Sum("value"))["value__sum"]if recent_invites is None:return 0@@ -120,7 +120,7 @@ def too_many_recent_realm_invites(realm: Realm, num_invitees: int) -> bool:if realm.icon_source == Realm.ICON_FROM_GRAVATAR:warning_flags.append("no-realm-icon")- if realm.date_created >= timezone_now() - datetime.timedelta(hours=1):+ if realm.date_created >= timezone_now() - timedelta(hours=1):warning_flags.append("realm-created-in-last-hour")current_user_count = len(UserProfile.objects.filter(realm=realm, is_bot=False, is_active=True))@@ -181,7 +181,7 @@ def check_invite_limit(realm: Realm, num_invitees: int) -> None:)default_max = settings.INVITES_DEFAULT_REALM_DAILY_MAX- newrealm_age = datetime.timedelta(days=settings.INVITES_NEW_REALM_DAYS)+ newrealm_age = timedelta(days=settings.INVITES_NEW_REALM_DAYS)if realm.date_created <= timezone_now() - newrealm_age:# If this isn't a "newly-created" realm, we're done. The# remaining code applies an aggregate limit across all@@ -235,7 +235,7 @@ def do_invite_users(realm = user_profile.realmif not realm.invite_required:# Inhibit joining an open realm to send spam invitations.- min_age = datetime.timedelta(days=settings.INVITES_MIN_USER_AGE_DAYS)+ min_age = timedelta(days=settings.INVITES_MIN_USER_AGE_DAYS)if user_profile.date_joined > timezone_now() - min_age and not user_profile.is_realm_admin:raise InvitationError(_(diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.pyindex b83e8769078..0f7a4920cdf 100644--- a/zerver/actions/message_edit.py+++ b/zerver/actions/message_edit.py@@ -1,6 +1,6 @@-import datetimeimport itertoolsfrom collections import defaultdict+from datetime import timedeltafrom typing import AbstractSet, Any, Dict, Iterable, List, Optional, Set, Tuplefrom django.conf import settings@@ -1151,8 +1151,7 @@ def check_time_limit_for_change_all_propagate_mode(Message.objects.filter(# Uses index: zerver_message_pkeyid__in=accessible_messages_in_topic,- date_sent__gt=timezone_now()- - datetime.timedelta(seconds=message_move_deadline_seconds),+ date_sent__gt=timezone_now() - timedelta(seconds=message_move_deadline_seconds),).order_by("date_sent").values_list("id", flat=True)@@ -1164,7 +1163,7 @@ def check_time_limit_for_change_all_propagate_mode(.order_by("id").values_list("id", "date_sent"))- oldest_allowed_message_date = timezone_now() - datetime.timedelta(+ oldest_allowed_message_date = timezone_now() - timedelta(seconds=message_move_deadline_seconds)messages_allowed_to_move = [@@ -1235,7 +1234,7 @@ def check_update_message(edit_limit_buffer = 20if content is not None and user_profile.realm.message_content_edit_limit_seconds is not None:deadline_seconds = user_profile.realm.message_content_edit_limit_seconds + edit_limit_buffer- if (timezone_now() - message.date_sent) > datetime.timedelta(seconds=deadline_seconds):+ if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):raise JsonableError(_("The time limit for editing this message has passed"))# If there is a change to the topic, check that the user is allowed to@@ -1250,7 +1249,7 @@ def check_update_message(deadline_seconds = (user_profile.realm.move_messages_within_stream_limit_seconds + edit_limit_buffer)- if (timezone_now() - message.date_sent) > datetime.timedelta(seconds=deadline_seconds):+ if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):raise JsonableError(_("The time limit for editing this message's topic has passed."))rendering_result = None@@ -1318,7 +1317,7 @@ def check_update_message(deadline_seconds = (user_profile.realm.move_messages_between_streams_limit_seconds + edit_limit_buffer)- if (timezone_now() - message.date_sent) > datetime.timedelta(seconds=deadline_seconds):+ if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):raise JsonableError(_("The time limit for editing this message's stream has passed"))diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.pyindex d335083cb6c..5ba43d0480b 100644--- a/zerver/actions/message_send.py+++ b/zerver/actions/message_send.py@@ -1,7 +1,7 @@-import datetimeimport loggingfrom collections import defaultdictfrom dataclasses import dataclass+from datetime import timedeltafrom email.headerregistry import Addressfrom typing import (AbstractSet,@@ -818,7 +818,7 @@ def filter_presence_idle_user_ids(user_ids: Set[int]) -> List[int]:if not user_ids:return []- recent = timezone_now() - datetime.timedelta(seconds=settings.OFFLINE_THRESHOLD_SECS)+ recent = timezone_now() - timedelta(seconds=settings.OFFLINE_THRESHOLD_SECS)rows = UserPresence.objects.filter(user_profile_id__in=user_ids,last_active_time__gte=recent,@@ -1174,9 +1174,9 @@ def already_sent_mirrored_message_id(message: Message) -> Optional[int]:# For huddle messages, we use a 10-second window because the# timestamps aren't guaranteed to actually match between two# copies of the same message.- time_window = datetime.timedelta(seconds=10)+ time_window = timedelta(seconds=10)else:- time_window = datetime.timedelta(seconds=0)+ time_window = timedelta(seconds=0)messages = Message.objects.filter(# Uses index: zerver_message_realm_recipient_subject@@ -1370,7 +1370,7 @@ def send_rate_limited_pm_notification_to_bot_owner(# direct messages on a misconfigured integration, re-using the# UserProfile.last_reminder field, which is not used for bots.last_reminder = sender.last_reminder- waitperiod = datetime.timedelta(minutes=UserProfile.BOT_OWNER_STREAM_ALERT_WAITPERIOD)+ waitperiod = timedelta(minutes=UserProfile.BOT_OWNER_STREAM_ALERT_WAITPERIOD)if last_reminder and timezone_now() - last_reminder <= waitperiod:returndiff --git a/zerver/actions/muted_users.py b/zerver/actions/muted_users.pyindex 3ce10123bc7..b8a0a5f0762 100644--- a/zerver/actions/muted_users.py+++ b/zerver/actions/muted_users.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetimefrom typing import Optionalfrom django.utils.timezone import now as timezone_now@@ -12,7 +12,7 @@ from zerver.tornado.django_api import send_eventdef do_mute_user(user_profile: UserProfile,muted_user: UserProfile,- date_muted: Optional[datetime.datetime] = None,+ date_muted: Optional[datetime] = None,) -> None:if date_muted is None:date_muted = timezone_now()diff --git a/zerver/actions/presence.py b/zerver/actions/presence.pyindex a7204d57191..25031bec6c5 100644--- a/zerver/actions/presence.py+++ b/zerver/actions/presence.py@@ -1,5 +1,5 @@-import datetimeimport time+from datetime import datetime, timedeltafrom django.conf import settingsfrom django.db import transaction@@ -87,7 +87,7 @@ def consolidate_client(client: Client) -> Client:def do_update_user_presence(user_profile: UserProfile,client: Client,- log_time: datetime.datetime,+ log_time: datetime,status: int,*,force_send_update: bool = False,@@ -116,15 +116,15 @@ def do_update_user_presence(else:# The user was never active, so let's consider this large to go over any thresholds# we may have.- time_since_last_active = datetime.timedelta(days=1)+ time_since_last_active = timedelta(days=1)if presence.last_connected_time is not None:time_since_last_connected = log_time - presence.last_connected_timeelse:# Same approach as above.- time_since_last_connected = datetime.timedelta(days=1)+ time_since_last_connected = timedelta(days=1)assert (3 * settings.PRESENCE_PING_INTERVAL_SECS + 20) <= settings.OFFLINE_THRESHOLD_SECS- now_online = time_since_last_active > datetime.timedelta(+ now_online = time_since_last_active > timedelta(# Here, we decide whether the user is newly online, and we need to consider# sending an immediate presence update via the events system that this user is now online,# rather than waiting for other clients to poll the presence update.@@ -146,7 +146,7 @@ def do_update_user_presence(# times per minute with multiple connected browser windows.# We also need to be careful not to wrongly "update" the timestamp if we actually already# have newer presence than the reported log_time.- if not created and time_since_last_connected > datetime.timedelta(+ if not created and time_since_last_connected > timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS):presence.last_connected_time = log_time@@ -154,8 +154,7 @@ def do_update_user_presence(if (not createdand status == UserPresence.LEGACY_STATUS_ACTIVE_INT- and time_since_last_active- > datetime.timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS)+ and time_since_last_active > timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS)):presence.last_active_time = log_timeupdate_fields.append("last_active_time")@@ -184,7 +183,7 @@ def do_update_user_presence(def update_user_presence(user_profile: UserProfile,client: Client,- log_time: datetime.datetime,+ log_time: datetime,status: int,new_user_input: bool,) -> None:diff --git a/zerver/actions/scheduled_messages.py b/zerver/actions/scheduled_messages.pyindex 4a8416b4d97..cc5a9adbe46 100644--- a/zerver/actions/scheduled_messages.py+++ b/zerver/actions/scheduled_messages.py@@ -1,5 +1,5 @@-import datetimeimport logging+from datetime import datetime, timedeltafrom typing import List, Optional, Sequence, Tuplefrom django.conf import settings@@ -41,7 +41,7 @@ def check_schedule_message(message_to: List[int],topic_name: Optional[str],message_content: str,- deliver_at: datetime.datetime,+ deliver_at: datetime,realm: Optional[Realm] = None,forwarder_user_profile: Optional[UserProfile] = None,) -> int:@@ -125,7 +125,7 @@ def edit_scheduled_message(message_to: Optional[str],topic_name: Optional[str],message_content: Optional[str],- deliver_at: Optional[datetime.datetime],+ deliver_at: Optional[datetime],realm: Realm,) -> None:with transaction.atomic():@@ -269,7 +269,7 @@ def send_scheduled_message(scheduled_message: ScheduledMessage) -> None:raise UserDeactivatedError# Limit how late we're willing to send a scheduled message.- latest_send_time = scheduled_message.scheduled_timestamp + datetime.timedelta(+ latest_send_time = scheduled_message.scheduled_timestamp + timedelta(minutes=SCHEDULED_MESSAGE_LATE_CUTOFF_MINUTES)if timezone_now() > latest_send_time:diff --git a/zerver/actions/user_activity.py b/zerver/actions/user_activity.pyindex f13fabb6727..eb27444fa1e 100644--- a/zerver/actions/user_activity.py+++ b/zerver/actions/user_activity.py@@ -1,13 +1,11 @@-import datetime+from datetime import datetimefrom zerver.lib.queue import queue_json_publishfrom zerver.lib.timestamp import datetime_to_timestampfrom zerver.models import UserActivity, UserActivityInterval, UserProfile-def do_update_user_activity_interval(- user_profile: UserProfile, log_time: datetime.datetime-) -> None:+def do_update_user_activity_interval(user_profile: UserProfile, log_time: datetime) -> None:effective_end = log_time + UserActivityInterval.MIN_INTERVAL_LENGTH# This code isn't perfect, because with various races we might end# up creating two overlapping intervals, but that shouldn't happen@@ -32,7 +30,7 @@ def do_update_user_activity_interval(def do_update_user_activity(- user_profile_id: int, client_id: int, query: str, count: int, log_time: datetime.datetime+ user_profile_id: int, client_id: int, query: str, count: int, log_time: datetime) -> None:(activity, created) = UserActivity.objects.get_or_create(user_profile_id=user_profile_id,@@ -47,6 +45,6 @@ def do_update_user_activity(activity.save(update_fields=["last_visit", "count"])-def update_user_activity_interval(user_profile: UserProfile, log_time: datetime.datetime) -> None:+def update_user_activity_interval(user_profile: UserProfile, log_time: datetime) -> None:event = {"user_profile_id": user_profile.id, "time": datetime_to_timestamp(log_time)}queue_json_publish("user_activity_interval", event)diff --git a/zerver/actions/user_groups.py b/zerver/actions/user_groups.pyindex fceb2600bb7..d90f4b59833 100644--- a/zerver/actions/user_groups.py+++ b/zerver/actions/user_groups.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetimefrom typing import Dict, List, Mapping, Optional, Sequence, TypedDict, Unionimport django.db.utils@@ -27,7 +27,7 @@ from zerver.tornado.django_api import send_event, send_event_on_commitclass MemberGroupUserDict(TypedDict):id: introle: int- date_joined: datetime.datetime+ date_joined: datetime@transaction.atomicdiff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.pyindex b17efd148ad..e73f014fa77 100644--- a/zerver/actions/user_settings.py+++ b/zerver/actions/user_settings.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom typing import Iterable, Optional, Unionfrom django.conf import settings@@ -404,9 +404,9 @@ def update_scheduled_email_notifications_time(user_profile=user_profile)- scheduled_timestamp_change = datetime.timedelta(- seconds=new_batching_period- ) - datetime.timedelta(seconds=old_batching_period)+ scheduled_timestamp_change = timedelta(seconds=new_batching_period) - timedelta(+ seconds=old_batching_period+ )existing_scheduled_emails.update(scheduled_timestamp=F("scheduled_timestamp") + scheduled_timestamp_change@@ -566,7 +566,7 @@ def do_change_user_setting(# We add a small additional offset as a fudge factor in# case of clock skew.status = UserPresence.LEGACY_STATUS_IDLE_INT- presence_time = timezone_now() - datetime.timedelta(+ presence_time = timezone_now() - timedelta(seconds=settings.OFFLINE_THRESHOLD_SECS + 120)diff --git a/zerver/actions/user_topics.py b/zerver/actions/user_topics.pyindex e454e52194b..505a1859054 100644--- a/zerver/actions/user_topics.py+++ b/zerver/actions/user_topics.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetimefrom typing import Any, Dict, List, Optionalfrom django.utils.timezone import now as timezone_now@@ -18,7 +18,7 @@ def bulk_do_set_user_topic_visibility_policy(topic: str,*,visibility_policy: int,- last_updated: Optional[datetime.datetime] = None,+ last_updated: Optional[datetime] = None,skip_muted_topics_event: bool = False,) -> None:if last_updated is None:@@ -66,7 +66,7 @@ def do_set_user_topic_visibility_policy(topic: str,*,visibility_policy: int,- last_updated: Optional[datetime.datetime] = None,+ last_updated: Optional[datetime] = None,skip_muted_topics_event: bool = False,) -> None:# For conciseness, this function should be used when a singlediff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.pyindex 4f3fd32934e..5c069cb9730 100644--- a/zerver/data_import/slack.py+++ b/zerver/data_import/slack.py@@ -1,4 +1,3 @@-import datetimeimport loggingimport osimport posixpath@@ -7,6 +6,7 @@ import secretsimport shutilimport zipfilefrom collections import defaultdict+from datetime import datetime, timezonefrom email.headerregistry import Addressfrom typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Type, TypeVarfrom urllib.parse import urlsplit@@ -972,9 +972,7 @@ def channel_message_to_zerver_message(# a counter among topics on that day.topic_name = "imported from Slack"if convert_slack_threads and "thread_ts" in message:- thread_ts = datetime.datetime.fromtimestamp(- float(message["thread_ts"]), tz=datetime.timezone.utc- )+ thread_ts = datetime.fromtimestamp(float(message["thread_ts"]), tz=timezone.utc)thread_ts_str = thread_ts.strftime(r"%Y/%m/%d %H:%M:%S")# The topic name is "2015-08-18 Slack thread 2", where the counter at the end is to disambiguate# threads with the same date.diff --git a/zerver/decorator.py b/zerver/decorator.pyindex 3074d194292..c8ab7410de5 100644--- a/zerver/decorator.py+++ b/zerver/decorator.py@@ -1,7 +1,7 @@import base64-import datetimeimport loggingimport urllib+from datetime import datetimefrom functools import wrapsfrom io import BytesIOfrom typing import (@@ -948,7 +948,7 @@ def internal_notify_view(return _wrapped_view_func-def to_utc_datetime(var_name: str, timestamp: str) -> datetime.datetime:+def to_utc_datetime(var_name: str, timestamp: str) -> datetime:return timestamp_to_datetime(float(timestamp))diff --git a/zerver/lib/cache_helpers.py b/zerver/lib/cache_helpers.pyindex d7ce7c9eea0..d83c2a40bb6 100644--- a/zerver/lib/cache_helpers.py+++ b/zerver/lib/cache_helpers.py@@ -1,6 +1,6 @@# See https://zulip.readthedocs.io/en/latest/subsystems/caching.html for docs-import datetimeimport logging+from datetime import timedeltafrom typing import Any, Callable, Dict, Iterable, Tuplefrom django.conf import settings@@ -64,7 +64,7 @@ def get_active_realm_ids() -> ValuesQuerySet[RealmCount, int]:worth of cache work (where N is the number of default streams fora new organization)."""- date = timezone_now() - datetime.timedelta(days=2)+ date = timezone_now() - timedelta(days=2)return (RealmCount.objects.filter(end_time__gte=date, property="1day_actives::day", value__gt=0).distinct("realm_id")diff --git a/zerver/lib/compatibility.py b/zerver/lib/compatibility.pyindex 3fc4c69adc3..912345454ad 100644--- a/zerver/lib/compatibility.py+++ b/zerver/lib/compatibility.py@@ -1,6 +1,6 @@-import datetimeimport osimport re+from datetime import datetime, timedelta, timezonefrom typing import List, Optional, Tuplefrom django.conf import settings@@ -14,8 +14,8 @@ from zerver.signals import get_device_browser# LAST_SERVER_UPGRADE_TIME is the last time the server had a version deployed.if settings.PRODUCTION: # nocoveragetimestamp = os.path.basename(os.path.abspath(settings.DEPLOY_ROOT))- LAST_SERVER_UPGRADE_TIME = datetime.datetime.strptime(timestamp, "%Y-%m-%d-%H-%M-%S").replace(- tzinfo=datetime.timezone.utc+ LAST_SERVER_UPGRADE_TIME = datetime.strptime(timestamp, "%Y-%m-%d-%H-%M-%S").replace(+ tzinfo=timezone.utc)else:LAST_SERVER_UPGRADE_TIME = timezone_now()@@ -28,18 +28,14 @@ def is_outdated_server(user_profile: Optional[UserProfile]) -> bool:# someone has upgraded in the last year but to a release more than# a year old.git_version_path = os.path.join(settings.DEPLOY_ROOT, "version.py")- release_build_time = datetime.datetime.fromtimestamp(- os.path.getmtime(git_version_path), datetime.timezone.utc- )+ release_build_time = datetime.fromtimestamp(os.path.getmtime(git_version_path), timezone.utc)version_no_newer_than = min(LAST_SERVER_UPGRADE_TIME, release_build_time)- deadline = version_no_newer_than + datetime.timedelta(- days=settings.SERVER_UPGRADE_NAG_DEADLINE_DAYS- )+ deadline = version_no_newer_than + timedelta(days=settings.SERVER_UPGRADE_NAG_DEADLINE_DAYS)if user_profile is None or not user_profile.is_realm_admin:# Administrators get warned at the deadline; all users 30 days later.- deadline = deadline + datetime.timedelta(days=30)+ deadline = deadline + timedelta(days=30)if timezone_now() > deadline:return Truediff --git a/zerver/lib/digest.py b/zerver/lib/digest.pyindex 4197999fc60..d0e91cdf783 100644--- a/zerver/lib/digest.py+++ b/zerver/lib/digest.py@@ -1,8 +1,8 @@-import datetimeimport functoolsimport heapqimport loggingfrom collections import defaultdict+from datetime import datetime, timedelta, timezonefrom typing import Any, Collection, Dict, Iterator, List, Optional, Set, Tuplefrom django.conf import settings@@ -88,13 +88,13 @@ class DigestTopic:# Changes to this should also be reflected in# zerver/worker/queue_processors.py:DigestWorker.consume()-def queue_digest_user_ids(user_ids: List[int], cutoff: datetime.datetime) -> None:+def queue_digest_user_ids(user_ids: List[int], cutoff: datetime) -> None:# Convert cutoff to epoch seconds for transit.event = {"user_ids": user_ids, "cutoff": cutoff.strftime("%s")}queue_json_publish("digest_emails", event)-def enqueue_emails(cutoff: datetime.datetime) -> None:+def enqueue_emails(cutoff: datetime) -> None:if not settings.SEND_DIGEST_EMAILS:return@@ -105,10 +105,10 @@ def enqueue_emails(cutoff: datetime.datetime) -> None:_enqueue_emails_for_realm(realm, cutoff)-def _enqueue_emails_for_realm(realm: Realm, cutoff: datetime.datetime) -> None:+def _enqueue_emails_for_realm(realm: Realm, cutoff: datetime) -> None:# This should only be called directly by tests. Use enqueue_emails# to process all realms that are set up for processing on any given day.- twelve_hours_ago = timezone_now() - datetime.timedelta(hours=12)+ twelve_hours_ago = timezone_now() - timedelta(hours=12)target_users = (UserProfile.objects.filter(@@ -174,7 +174,7 @@ def maybe_clear_recent_topics_cache(realm_id: int, cutoff: float) -> None:def get_recent_topics(realm_id: int,stream_id: int,- cutoff_date: datetime.datetime,+ cutoff_date: datetime,) -> List[DigestTopic]:# Gather information about topic conversations, then# classify by:@@ -237,7 +237,7 @@ def get_hot_topics(return hot_topics-def get_recently_created_streams(realm: Realm, threshold: datetime.datetime) -> List[Stream]:+def get_recently_created_streams(realm: Realm, threshold: datetime) -> List[Stream]:fields = ["id", "name", "is_web_public", "invite_only"]return list(get_active_streams(realm).filter(date_created__gt=threshold).only(*fields))@@ -270,7 +270,7 @@ def enough_traffic(hot_conversations: str, new_streams: int) -> bool:return bool(hot_conversations or new_streams)-def get_user_stream_map(user_ids: List[int], cutoff_date: datetime.datetime) -> Dict[int, Set[int]]:+def get_user_stream_map(user_ids: List[int], cutoff_date: datetime) -> Dict[int, Set[int]]:"""Skipping streams where the user's subscription status has changedwhen constructing digests is critical to ensure correctness forstreams without shared history, guest users, and long-term idle@@ -337,7 +337,7 @@ def bulk_get_digest_context(assert user.realm_id == realm.id# Convert from epoch seconds to a datetime object.- cutoff_date = datetime.datetime.fromtimestamp(int(cutoff), tz=datetime.timezone.utc)+ cutoff_date = datetime.fromtimestamp(int(cutoff), tz=timezone.utc)maybe_clear_recent_topics_cache(realm.id, cutoff)diff --git a/zerver/lib/export.py b/zerver/lib/export.pyindex 845deeaaaae..c9732b83964 100644--- a/zerver/lib/export.py+++ b/zerver/lib/export.py@@ -6,7 +6,6 @@# it the lists in `ALL_ZULIP_TABLES` and similar data structures and# (2) if it doesn't belong in EXCLUDED_TABLES, add a Config object for# it to get_realm_config.-import datetimeimport globimport loggingimport os@@ -14,6 +13,7 @@ import shutilimport subprocessimport tempfilefrom contextlib import suppress+from datetime import datetimefrom functools import lru_cachefrom typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypedDict@@ -436,7 +436,7 @@ def floatify_datetime_fields(data: TableData, table: TableName) -> None:dt = item[field]if dt is None:continue- assert isinstance(dt, datetime.datetime)+ assert isinstance(dt, datetime)assert not timezone_is_naive(dt)item[field] = dt.timestamp()diff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.pyindex 145343bbb9c..d2898de7369 100644--- a/zerver/lib/import_realm.py+++ b/zerver/lib/import_realm.py@@ -1,8 +1,8 @@-import datetimeimport loggingimport osimport shutilfrom concurrent.futures import ProcessPoolExecutor, as_completed+from datetime import datetime, timezonefrom mimetypes import guess_typefrom typing import Any, Dict, List, Optional, Tuple@@ -169,9 +169,7 @@ def fix_datetime_fields(data: TableData, table: TableName) -> None:for item in data[table]:for field_name in DATE_FIELDS[table]:if item[field_name] is not None:- item[field_name] = datetime.datetime.fromtimestamp(- item[field_name], tz=datetime.timezone.utc- )+ item[field_name] = datetime.fromtimestamp(item[field_name], tz=timezone.utc)def fix_upload_links(data: TableData, message_table: TableName) -> None:diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.pyindex 53bbb32b16d..576f12d0c44 100644--- a/zerver/lib/markdown/__init__.py+++ b/zerver/lib/markdown/__init__.py@@ -1,7 +1,6 @@# Zulip's main Markdown implementation. See docs/subsystems/markdown.md for# detailed documentation on our Markdown syntax.import cgi-import datetimeimport htmlimport loggingimport mimetypes@@ -11,6 +10,7 @@ import urllibimport urllib.parsefrom collections import dequefrom dataclasses import dataclass+from datetime import datetime, timezonefrom functools import lru_cachefrom typing import (Any,@@ -1403,9 +1403,7 @@ class Timestamp(markdown.inlinepatterns.Pattern):timestamp = dateutil.parser.parse(time_input_string, tzinfos=common_timezones)except ValueError:try:- timestamp = datetime.datetime.fromtimestamp(- float(time_input_string), tz=datetime.timezone.utc- )+ timestamp = datetime.fromtimestamp(float(time_input_string), tz=timezone.utc)except ValueError:timestamp = None@@ -1420,9 +1418,9 @@ class Timestamp(markdown.inlinepatterns.Pattern):# Use HTML5 <time> element for valid timestamps.time_element = Element("time")if timestamp.tzinfo:- timestamp = timestamp.astimezone(datetime.timezone.utc)+ timestamp = timestamp.astimezone(timezone.utc)else:- timestamp = timestamp.replace(tzinfo=datetime.timezone.utc)+ timestamp = timestamp.replace(tzinfo=timezone.utc)time_element.set("datetime", timestamp.isoformat().replace("+00:00", "Z"))# Set text to initial input, so simple clients translating# HTML to text will at least display something.diff --git a/zerver/lib/message.py b/zerver/lib/message.pyindex 16c9b76818a..201fa6917fc 100644--- a/zerver/lib/message.py+++ b/zerver/lib/message.py@@ -1,7 +1,7 @@import copy-import datetimeimport zlibfrom dataclasses import dataclass, field+from datetime import datetime, timedeltafrom typing import (Any,Collection,@@ -203,7 +203,7 @@ class SendMessageRequest:links_for_embed: Set[str]widget_content: Optional[Dict[str, Any]]submessages: List[Dict[str, Any]] = field(default_factory=list)- deliver_at: Optional[datetime.datetime] = None+ deliver_at: Optional[datetime] = Nonedelivery_type: Optional[str] = Nonelimit_unread_user_ids: Optional[Set[int]] = Noneservice_queue_events: Optional[Dict[str, List[Dict[str, Any]]]] = None@@ -561,11 +561,11 @@ class MessageDict:@staticmethoddef build_message_dict(message_id: int,- last_edit_time: Optional[datetime.datetime],+ last_edit_time: Optional[datetime],edit_history_json: Optional[str],content: str,topic_name: str,- date_sent: datetime.datetime,+ date_sent: datetime,rendered_content: Optional[str],rendered_content_version: Optional[int],sender_id: int,@@ -1492,7 +1492,7 @@ def add_message_to_unread_msgs(def estimate_recent_messages(realm: Realm, hours: int) -> int:stat = COUNT_STATS["messages_sent:is_bot:hour"]- d = timezone_now() - datetime.timedelta(hours=hours)+ d = timezone_now() - timedelta(hours=hours)return (RealmCount.objects.filter(property=stat.property, end_time__gt=d, realm=realm).aggregate(Sum("value")diff --git a/zerver/lib/muted_users.py b/zerver/lib/muted_users.pyindex 07548e08fcb..d7f25ae9f0a 100644--- a/zerver/lib/muted_users.py+++ b/zerver/lib/muted_users.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetimefrom typing import Dict, List, Optional, Setfrom zerver.lib.cache import cache_with_key, get_muting_users_cache_key@@ -21,9 +21,7 @@ def get_user_mutes(user_profile: UserProfile) -> List[Dict[str, int]]:]-def add_user_mute(- user_profile: UserProfile, muted_user: UserProfile, date_muted: datetime.datetime-) -> None:+def add_user_mute(user_profile: UserProfile, muted_user: UserProfile, date_muted: datetime) -> None:MutedUser.objects.create(user_profile=user_profile,muted_user=muted_user,diff --git a/zerver/lib/presence.py b/zerver/lib/presence.pyindex 1cd8ae74d4d..bb30b11ae6c 100644--- a/zerver/lib/presence.py+++ b/zerver/lib/presence.py@@ -1,6 +1,6 @@-import datetimeimport timefrom collections import defaultdict+from datetime import datetime, timedeltafrom typing import Any, Dict, Mapping, Optional, Sequence, Setfrom django.conf import settings@@ -45,14 +45,14 @@ def get_presence_dicts_for_rows(def user_presence_datetime_with_date_joined_default(- dt: Optional[datetime.datetime], date_joined: datetime.datetime-) -> datetime.datetime:+ dt: Optional[datetime], date_joined: datetime+) -> datetime:"""Our data models support UserPresence objects not having Nonevalues for last_active_time/last_connected_time. The legacy APIhowever has always sent timestamps, so for backwardcompatibility we cannot send such values through the API and need- to default to a sane datetime.+ to default to a saneThis helper functions expects to take a last_active_time orlast_connected_time value and the date_joined of the user, which@@ -65,7 +65,7 @@ def user_presence_datetime_with_date_joined_default(def get_modern_user_presence_info(- last_active_time: datetime.datetime, last_connected_time: datetime.datetime+ last_active_time: datetime, last_connected_time: datetime) -> Dict[str, Any]:# TODO: Do further bandwidth optimizations to this structure.result = {}@@ -75,7 +75,7 @@ def get_modern_user_presence_info(def get_legacy_user_presence_info(- last_active_time: datetime.datetime, last_connected_time: datetime.datetime+ last_active_time: datetime, last_connected_time: datetime) -> Dict[str, Any]:"""Reformats the modern UserPresence data structure so that legacy@@ -106,7 +106,7 @@ def get_legacy_user_presence_info(def format_legacy_presence_dict(- last_active_time: datetime.datetime, last_connected_time: datetime.datetime+ last_active_time: datetime, last_connected_time: datetime) -> Dict[str, Any]:"""This function assumes it's being called right after the presence object was updated,@@ -114,7 +114,7 @@ def format_legacy_presence_dict("""if (last_active_time- + datetime.timedelta(seconds=settings.PRESENCE_LEGACY_EVENT_OFFSET_FOR_ACTIVITY_SECONDS)+ + timedelta(seconds=settings.PRESENCE_LEGACY_EVENT_OFFSET_FOR_ACTIVITY_SECONDS)>= last_connected_time):status = UserPresence.LEGACY_STATUS_ACTIVE@@ -154,7 +154,7 @@ def get_presence_for_user(def get_presence_dict_by_realm(realm: Realm, slim_presence: bool = False, requesting_user_profile: Optional[UserProfile] = None) -> Dict[str, Dict[str, Any]]:- two_weeks_ago = timezone_now() - datetime.timedelta(weeks=2)+ two_weeks_ago = timezone_now() - timedelta(weeks=2)query = UserPresence.objects.filter(realm_id=realm.id,last_connected_time__gte=two_weeks_ago,diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex 79a9e89bfdd..5b39cd20daf 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -1,9 +1,9 @@-import datetimeimport hashlibimport loggingimport osimport smtplibfrom contextlib import suppress+from datetime import timedeltafrom email.headerregistry import Addressfrom email.parser import Parserfrom email.policy import default@@ -346,7 +346,7 @@ def send_future_email(from_address: Optional[str] = None,language: Optional[str] = None,context: Mapping[str, Any] = {},- delay: datetime.timedelta = datetime.timedelta(0),+ delay: timedelta = timedelta(0),) -> None:template_name = template_prefix.split("/")[-1]email_fields = {diff --git a/zerver/lib/stream_traffic.py b/zerver/lib/stream_traffic.pyindex 812df78a1e7..cacefa3df8c 100644--- a/zerver/lib/stream_traffic.py+++ b/zerver/lib/stream_traffic.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetime, timedeltafrom typing import Dict, Optional, Setfrom django.db.models import Sum@@ -15,7 +15,7 @@ def get_streams_traffic(stream_ids: Set[int], realm: Realm) -> Optional[Dict[intreturn Nonestat = COUNT_STATS["messages_in_stream:is_bot:day"]- traffic_from = timezone_now() - datetime.timedelta(days=28)+ traffic_from = timezone_now() - timedelta(days=28)query = StreamCount.objects.filter(# The realm_id is important, as it makes this significantly better-indexed@@ -41,7 +41,7 @@ STREAM_TRAFFIC_CALCULATION_MIN_AGE_DAYS = 7def get_average_weekly_stream_traffic(- stream_id: int, stream_date_created: datetime.datetime, recent_traffic: Dict[int, int]+ stream_id: int, stream_date_created: datetime, recent_traffic: Dict[int, int]) -> Optional[int]:try:stream_traffic = recent_traffic[stream_id]diff --git a/zerver/lib/timestamp.py b/zerver/lib/timestamp.pyindex 9098fcf6f9e..dfc61df21c0 100644--- a/zerver/lib/timestamp.py+++ b/zerver/lib/timestamp.py@@ -1,49 +1,49 @@-import datetime+from datetime import datetime, timedelta, timezoneclass TimeZoneNotUTCError(Exception):pass-def verify_UTC(dt: datetime.datetime) -> None:- if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) != datetime.timezone.utc.utcoffset(dt):+def verify_UTC(dt: datetime) -> None:+ if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) != timezone.utc.utcoffset(dt):raise TimeZoneNotUTCError(f"Datetime {dt} does not have a UTC time zone.")-def convert_to_UTC(dt: datetime.datetime) -> datetime.datetime:+def convert_to_UTC(dt: datetime) -> datetime:if dt.tzinfo is None:- return dt.replace(tzinfo=datetime.timezone.utc)- return dt.astimezone(datetime.timezone.utc)+ return dt.replace(tzinfo=timezone.utc)+ return dt.astimezone(timezone.utc)-def floor_to_hour(dt: datetime.datetime) -> datetime.datetime:+def floor_to_hour(dt: datetime) -> datetime:verify_UTC(dt)- return datetime.datetime(*dt.timetuple()[:4], tzinfo=datetime.timezone.utc)+ return datetime(*dt.timetuple()[:4], tzinfo=timezone.utc)-def floor_to_day(dt: datetime.datetime) -> datetime.datetime:+def floor_to_day(dt: datetime) -> datetime:verify_UTC(dt)- return datetime.datetime(*dt.timetuple()[:3], tzinfo=datetime.timezone.utc)+ return datetime(*dt.timetuple()[:3], tzinfo=timezone.utc)-def ceiling_to_hour(dt: datetime.datetime) -> datetime.datetime:+def ceiling_to_hour(dt: datetime) -> datetime:floor = floor_to_hour(dt)if floor == dt:return floor- return floor + datetime.timedelta(hours=1)+ return floor + timedelta(hours=1)-def ceiling_to_day(dt: datetime.datetime) -> datetime.datetime:+def ceiling_to_day(dt: datetime) -> datetime:floor = floor_to_day(dt)if floor == dt:return floor- return floor + datetime.timedelta(days=1)+ return floor + timedelta(days=1)-def timestamp_to_datetime(timestamp: float) -> datetime.datetime:- return datetime.datetime.fromtimestamp(float(timestamp), tz=datetime.timezone.utc)+def timestamp_to_datetime(timestamp: float) -> datetime:+ return datetime.fromtimestamp(float(timestamp), tz=timezone.utc)-def datetime_to_timestamp(dt: datetime.datetime) -> int:+def datetime_to_timestamp(dt: datetime) -> int:verify_UTC(dt)return int(dt.timestamp())diff --git a/zerver/lib/types.py b/zerver/lib/types.pyindex 7d79a5b7011..a74bd8109c0 100644--- a/zerver/lib/types.py+++ b/zerver/lib/types.py@@ -1,5 +1,5 @@-import datetimefrom dataclasses import dataclass, field+from datetime import datetimefrom typing import Any, Callable, Dict, List, Optional, Tuple, TypedDict, TypeVar, Unionfrom django_stubs_ext import StrPromise@@ -138,7 +138,7 @@ class RawStreamDict(TypedDict):"""can_remove_subscribers_group_id: int- date_created: datetime.datetime+ date_created: datetimedescription: strfirst_message_id: Optional[int]history_public_to_subscribers: bool@@ -309,7 +309,7 @@ class RawUserDict(TypedDict):is_billing_admin: boolis_bot: booltimezone: str- date_joined: datetime.datetime+ date_joined: datetimebot_owner_id: Optional[int]delivery_email: strbot_type: Optional[int]diff --git a/zerver/lib/user_topics.py b/zerver/lib/user_topics.pyindex 208cfd7aa36..a5b64aa2b03 100644--- a/zerver/lib/user_topics.py+++ b/zerver/lib/user_topics.py@@ -1,6 +1,6 @@-import datetimeimport loggingfrom collections import defaultdict+from datetime import datetimefrom typing import Callable, Dict, List, Optional, Tuple, TypedDictfrom django.db import transaction@@ -81,7 +81,7 @@ def set_topic_visibility_policy(user_profile: UserProfile,topics: List[List[str]],visibility_policy: int,- last_updated: Optional[datetime.datetime] = None,+ last_updated: Optional[datetime] = None,) -> None:"""This is only used in tests.@@ -132,7 +132,7 @@ def bulk_set_user_topic_visibility_policy_in_database(*,visibility_policy: int,recipient_id: Optional[int] = None,- last_updated: Optional[datetime.datetime] = None,+ last_updated: Optional[datetime] = None,) -> List[UserProfile]:# returns the list of user_profiles whose user_topic row# is either deleted, updated, or created.diff --git a/zerver/management/commands/delete_old_unclaimed_attachments.py b/zerver/management/commands/delete_old_unclaimed_attachments.pyindex 3271d53b71a..83ce211ea02 100644--- a/zerver/management/commands/delete_old_unclaimed_attachments.py+++ b/zerver/management/commands/delete_old_unclaimed_attachments.py@@ -1,5 +1,5 @@-import datetimefrom argparse import ArgumentParser+from datetime import timedeltafrom typing import Anyfrom django.core.management.base import BaseCommand, CommandError@@ -70,7 +70,7 @@ class Command(BaseCommand):raise CommandError("This was a dry run. Pass -f to actually delete.")def clean_attachment_upload_backend(self, dry_run: bool = True) -> None:- cutoff = timezone_now() - datetime.timedelta(minutes=5)+ cutoff = timezone_now() - timedelta(minutes=5)print(f"Removing extra files in storage black-end older than {cutoff.isoformat()}")to_delete = []for path_id, modified_at in all_message_attachments():diff --git a/zerver/management/commands/enqueue_digest_emails.py b/zerver/management/commands/enqueue_digest_emails.pyindex 3373bdfcd9b..7629ff7ea0f 100644--- a/zerver/management/commands/enqueue_digest_emails.py+++ b/zerver/management/commands/enqueue_digest_emails.py@@ -1,5 +1,5 @@-import datetimeimport logging+from datetime import timedeltafrom typing import Anyfrom django.conf import settings@@ -22,5 +22,5 @@ in a while.@overridedef handle(self, *args: Any, **options: Any) -> None:- cutoff = timezone_now() - datetime.timedelta(days=DIGEST_CUTOFF)+ cutoff = timezone_now() - timedelta(days=DIGEST_CUTOFF)enqueue_emails(cutoff)diff --git a/zerver/migrations/0262_mutedtopic_date_muted.py b/zerver/migrations/0262_mutedtopic_date_muted.pyindex 5f904d99e9b..c7989655073 100644--- a/zerver/migrations/0262_mutedtopic_date_muted.py+++ b/zerver/migrations/0262_mutedtopic_date_muted.py@@ -1,5 +1,5 @@# Generated by Django 1.11.26 on 2020-01-17 15:26-import datetime+from datetime import datetime, timezonefrom django.db import migrations, models@@ -13,8 +13,6 @@ class Migration(migrations.Migration):migrations.AddField(model_name="mutedtopic",name="date_muted",- field=models.DateTimeField(- default=datetime.datetime(2020, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)- ),+ field=models.DateTimeField(default=datetime(2020, 1, 1, 0, 0, tzinfo=timezone.utc)),),]diff --git a/zerver/models.py b/zerver/models.pyindex da5eb86d558..05ff6c20cbe 100644--- a/zerver/models.py+++ b/zerver/models.py@@ -1,12 +1,11 @@# https://github.com/typeddjango/django-stubs/issues/1698# mypy: disable-error-code="explicit-override"-import datetimeimport hashlibimport secretsimport timefrom collections import defaultdict-from datetime import timedelta+from datetime import datetime, timedelta, timezonefrom email.headerregistry import Addressfrom enum import Enumfrom typing import (@@ -2598,7 +2597,7 @@ def filter_to_valid_prereg_users(assert invite_expires_in_minutes is not Noneif not isinstance(invite_expires_in_minutes, UnspecifiedValue):- lowest_datetime = timezone_now() - datetime.timedelta(minutes=invite_expires_in_minutes)+ lowest_datetime = timezone_now() - timedelta(minutes=invite_expires_in_minutes)return query.filter(invited_at__gte=lowest_datetime)else:return query.filter(@@ -2880,9 +2879,7 @@ class UserTopic(models.Model):# The default value for last_updated is a few weeks before tracking# of when topics were muted was first introduced. It's designed# to be obviously incorrect so that one can tell it's backfilled data.- last_updated = models.DateTimeField(- default=datetime.datetime(2020, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)- )+ last_updated = models.DateTimeField(default=datetime(2020, 1, 1, 0, 0, tzinfo=timezone.utc))class VisibilityPolicy(models.IntegerChoices):# A normal muted topic. No notifications and unreads hidden.@@ -3979,7 +3976,7 @@ def get_old_unclaimed_attachments(or both - depending on whether some, all or none of the messageslinking to it have been archived."""- delta_weeks_ago = timezone_now() - datetime.timedelta(weeks=weeks_ago)+ delta_weeks_ago = timezone_now() - timedelta(weeks=weeks_ago)# The Attachment vs ArchivedAttachment queries are asymmetric because only# Attachment has the scheduled_messages relation.@@ -4379,7 +4376,7 @@ class UserActivity(models.Model):class UserActivityInterval(models.Model):- MIN_INTERVAL_LENGTH = datetime.timedelta(minutes=15)+ MIN_INTERVAL_LENGTH = timedelta(minutes=15)user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE)start = models.DateTimeField("start time", db_index=True)diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex d15736f7d7c..95b0e50e8f0 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -1,6 +1,5 @@import base64import copy-import datetimeimport jsonimport osimport re@@ -9,6 +8,7 @@ import timeimport urllibfrom abc import ABC, abstractmethodfrom contextlib import contextmanager+from datetime import timedeltafrom email.headerregistry import Addressfrom typing import (TYPE_CHECKING,@@ -1283,7 +1283,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):email=hamlet.delivery_email, name="Full Name")self.assert_length(mail.outbox, 0)- self.user_profile.date_joined = timezone_now() - datetime.timedelta(+ self.user_profile.date_joined = timezone_now() - timedelta(seconds=JUST_CREATED_THRESHOLD + 1)self.user_profile.save()@@ -1924,7 +1924,7 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):invite_expires_in_minutes=invite_expires_in_minutes,invite_as=PreregistrationUser.INVITE_AS["REALM_ADMIN"],)- now = timezone_now() + datetime.timedelta(days=3)+ now = timezone_now() + timedelta(days=3)subdomain = "zulip"realm = get_realm("zulip")@@ -4500,7 +4500,7 @@ class GoogleAuthBackendTest(SocialAuthBase):mobile_flow_otp = "1234abcd" * 8account_data_dict = self.get_account_data_dict(email=self.email, name="Full Name")self.assert_length(mail.outbox, 0)- self.user_profile.date_joined = timezone_now() - datetime.timedelta(+ self.user_profile.date_joined = timezone_now() - timedelta(seconds=JUST_CREATED_THRESHOLD + 1)self.user_profile.save()@@ -5643,7 +5643,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):def test_login_mobile_flow_otp_success_email(self) -> None:user_profile = self.example_user("hamlet")email = user_profile.delivery_email- user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)+ user_profile.date_joined = timezone_now() - timedelta(seconds=61)user_profile.save()mobile_flow_otp = "1234abcd" * 8@@ -5692,7 +5692,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):user_profile = self.example_user("hamlet")email = user_profile.delivery_emailremote_user = Address(addr_spec=email).username- user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)+ user_profile.date_joined = timezone_now() - timedelta(seconds=61)user_profile.save()mobile_flow_otp = "1234abcd" * 8@@ -5744,7 +5744,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):def test_login_desktop_flow_otp_success_email(self) -> None:user_profile = self.example_user("hamlet")email = user_profile.delivery_email- user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)+ user_profile.date_joined = timezone_now() - timedelta(seconds=61)user_profile.save()desktop_flow_otp = "1234abcd" * 8@@ -5778,7 +5778,7 @@ class TestZulipRemoteUserBackend(DesktopFlowTestingLib, ZulipTestCase):user_profile = self.example_user("hamlet")email = user_profile.delivery_emailremote_user = Address(addr_spec=email).username- user_profile.date_joined = timezone_now() - datetime.timedelta(seconds=61)+ user_profile.date_joined = timezone_now() - timedelta(seconds=61)user_profile.save()desktop_flow_otp = "1234abcd" * 8diff --git a/zerver/tests/test_digest.py b/zerver/tests/test_digest.pyindex 5f474b2543b..c70f859781c 100644--- a/zerver/tests/test_digest.py+++ b/zerver/tests/test_digest.py@@ -1,5 +1,5 @@-import datetimeimport time+from datetime import datetime, timedelta, timezonefrom typing import List, Setfrom unittest import mock@@ -49,9 +49,9 @@ class TestDigestEmailMessages(ZulipTestCase):othello = self.example_user("othello")self.subscribe(othello, "Verona")- one_day_ago = timezone_now() - datetime.timedelta(days=1)+ one_day_ago = timezone_now() - timedelta(days=1)Message.objects.all().update(date_sent=one_day_ago)- one_hour_ago = timezone_now() - datetime.timedelta(seconds=3600)+ one_hour_ago = timezone_now() - timedelta(seconds=3600)cutoff = time.mktime(one_hour_ago.timetuple())@@ -169,9 +169,9 @@ class TestDigestEmailMessages(ZulipTestCase):self.subscribe(cordelia, "web_public_stream")self.subscribe(polonius, "web_public_stream")- one_day_ago = timezone_now() - datetime.timedelta(days=1)+ one_day_ago = timezone_now() - timedelta(days=1)Message.objects.all().update(date_sent=one_day_ago)- one_hour_ago = timezone_now() - datetime.timedelta(seconds=3600)+ one_hour_ago = timezone_now() - timedelta(seconds=3600)cutoff = time.mktime(one_hour_ago.timetuple())@@ -207,7 +207,7 @@ class TestDigestEmailMessages(ZulipTestCase):self.assert_length(RealmAuditLog.objects.all(), startlen + 1)def test_soft_deactivated_user_multiple_stream_senders(self) -> None:- one_day_ago = timezone_now() - datetime.timedelta(days=1)+ one_day_ago = timezone_now() - timedelta(days=1)Message.objects.all().update(date_sent=one_day_ago)digest_users = [@@ -236,7 +236,7 @@ class TestDigestEmailMessages(ZulipTestCase):self.simulate_stream_conversation("Scotland", senders)self.simulate_stream_conversation("Denmark", senders)- one_hour_ago = timezone_now() - datetime.timedelta(seconds=3600)+ one_hour_ago = timezone_now() - timedelta(seconds=3600)cutoff = time.mktime(one_hour_ago.timetuple())# When this test is run in isolation, one additional query is run which@@ -298,8 +298,8 @@ class TestDigestEmailMessages(ZulipTestCase):data = get_user_stream_map([user.id], one_hour_ago)return {Stream.objects.get(id=stream_id) for stream_id in data[user.id]}- two_hours_ago = timezone_now() - datetime.timedelta(hours=2)- one_hour_ago = timezone_now() - datetime.timedelta(hours=1)+ two_hours_ago = timezone_now() - timedelta(hours=2)+ one_hour_ago = timezone_now() - timedelta(hours=1)# Delete all RealmAuditLogs to start with a clean slate.RealmAuditLog.objects.all().delete()@@ -359,7 +359,7 @@ class TestDigestEmailMessages(ZulipTestCase):realm = get_realm("zulip")- cutoff = timezone_now() - datetime.timedelta(days=5)+ cutoff = timezone_now() - timedelta(days=5)with mock.patch("zerver.lib.digest.queue_digest_user_ids") as queue_mock:_enqueue_emails_for_realm(realm, cutoff)@@ -387,7 +387,7 @@ class TestDigestEmailMessages(ZulipTestCase):do_set_realm_property(realm, "digest_weekday", timezone_now().weekday(), acting_user=None)- cutoff = timezone_now() - datetime.timedelta(days=0)+ cutoff = timezone_now() - timedelta(days=0)with mock.patch("zerver.worker.queue_processors.bulk_handle_digest_email") as queue_mock:@@ -405,7 +405,7 @@ class TestDigestEmailMessages(ZulipTestCase):RealmAuditLog.objects.all().delete()# Turn on realm digest emails for all realmsRealm.objects.update(digest_emails_enabled=True)- cutoff = timezone_now() - datetime.timedelta(days=5)+ cutoff = timezone_now() - timedelta(days=5)realm = get_realm("zulip")users = self.active_human_users(realm)@@ -419,7 +419,7 @@ class TestDigestEmailMessages(ZulipTestCase):self.assert_length(users, num_queued_users)for user in users:- last_visit = timezone_now() - datetime.timedelta(days=1)+ last_visit = timezone_now() - timedelta(days=1)UserActivityInterval.objects.create(start=last_visit,end=last_visit,@@ -433,7 +433,7 @@ class TestDigestEmailMessages(ZulipTestCase):self.assertEqual(queue_mock.call_count, 0)# Now, backdate all our users activity.- last_visit = timezone_now() - datetime.timedelta(days=7)+ last_visit = timezone_now() - timedelta(days=7)UserActivityInterval.objects.all().update(start=last_visit, end=last_visit)with mock.patch("zerver.worker.queue_processors.bulk_handle_digest_email") as queue_mock:@@ -442,15 +442,15 @@ class TestDigestEmailMessages(ZulipTestCase):num_queued_users = len(queue_mock.call_args[0][0])self.assert_length(users, num_queued_users)- def tuesday(self) -> datetime.datetime:- return datetime.datetime(year=2016, month=1, day=5, tzinfo=datetime.timezone.utc)+ def tuesday(self) -> datetime:+ return datetime(year=2016, month=1, day=5, tzinfo=timezone.utc)@override_settings(SEND_DIGEST_EMAILS=False)def test_disabled(self) -> None:RealmAuditLog.objects.all().delete()tuesday = self.tuesday()- cutoff = tuesday - datetime.timedelta(days=5)+ cutoff = tuesday - timedelta(days=5)with time_machine.travel(tuesday, tick=False):with mock.patch("zerver.lib.digest.queue_digest_user_ids") as queue_mock:@@ -461,8 +461,8 @@ class TestDigestEmailMessages(ZulipTestCase):def test_only_enqueue_on_valid_day(self) -> None:RealmAuditLog.objects.all().delete()- not_tuesday = datetime.datetime(year=2016, month=1, day=6, tzinfo=datetime.timezone.utc)- cutoff = not_tuesday - datetime.timedelta(days=5)+ not_tuesday = datetime(year=2016, month=1, day=6, tzinfo=timezone.utc)+ cutoff = not_tuesday - timedelta(days=5)with time_machine.travel(not_tuesday, tick=False):with mock.patch("zerver.lib.digest.queue_digest_user_ids") as queue_mock:@@ -473,7 +473,7 @@ class TestDigestEmailMessages(ZulipTestCase):def test_no_email_digest_for_bots(self) -> None:RealmAuditLog.objects.all().delete()- cutoff = timezone_now() - datetime.timedelta(days=5)+ cutoff = timezone_now() - timedelta(days=5)realm = get_realm("zulip")realm.digest_emails_enabled = True@@ -503,7 +503,7 @@ class TestDigestEmailMessages(ZulipTestCase):@override_settings(SEND_DIGEST_EMAILS=True)def test_new_stream_link(self) -> None:Stream.objects.all().delete()- cutoff = timezone_now() - datetime.timedelta(days=5)+ cutoff = timezone_now() - timedelta(days=5)cordelia = self.example_user("cordelia")stream = create_stream_if_needed(cordelia.realm, "New stream")[0]stream.date_created = timezone_now()@@ -537,7 +537,7 @@ class TestDigestEmailMessages(ZulipTestCase):self.assertEqual(stream_count, 1)# Make the stream appear to be older.- stream.date_created = timezone_now() - datetime.timedelta(days=7)+ stream.date_created = timezone_now() - timedelta(days=7)stream.save()recently_created_streams = get_recently_created_streams(realm, cutoff)diff --git a/zerver/tests/test_email_change.py b/zerver/tests/test_email_change.pyindex dd4126c650a..14d4dff518c 100644--- a/zerver/tests/test_email_change.py+++ b/zerver/tests/test_email_change.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom email.headerregistry import Addressimport time_machine@@ -78,7 +78,7 @@ class EmailChangeTestCase(ZulipTestCase):user_profile=user_profile,realm=user_profile.realm,)- date_sent = now() - datetime.timedelta(days=2)+ date_sent = now() - timedelta(days=2)with time_machine.travel(date_sent, tick=False):url = create_confirmation_link(obj, Confirmation.EMAIL_CHANGE)@@ -361,9 +361,7 @@ class EmailChangeTestCase(ZulipTestCase):def test_configure_demo_organization_owner_email(self) -> None:desdemona = self.example_user("desdemona")- desdemona.realm.demo_organization_scheduled_deletion_date = now() + datetime.timedelta(- days=30- )+ desdemona.realm.demo_organization_scheduled_deletion_date = now() + timedelta(days=30)desdemona.realm.save()assert desdemona.realm.demo_organization_scheduled_deletion_date is not Nonediff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.pyindex 4d93864ba81..0a5b771b16c 100644--- a/zerver/tests/test_events.py+++ b/zerver/tests/test_events.py@@ -5,8 +5,8 @@# and zerver/lib/data_types.py systems for validating the schemas of# events; it also uses the OpenAPI tools to validate our documentation.import copy-import datetimeimport time+from datetime import timedeltafrom io import StringIOfrom typing import Any, Callable, Dict, List, Optional, Setfrom unittest import mock@@ -1454,7 +1454,7 @@ class NormalActionsTest(BaseAction):def test_presence_events_multiple_clients(self) -> None:now = timezone_now()- initial_presence = now - datetime.timedelta(days=365)+ initial_presence = now - timedelta(days=365)UserPresence.objects.create(user_profile=self.user_profile,realm=self.user_profile.realm,@@ -1490,7 +1490,7 @@ class NormalActionsTest(BaseAction):lambda: do_update_user_presence(self.user_profile,get_client("ZulipAndroid/1.0"),- timezone_now() + datetime.timedelta(seconds=301),+ timezone_now() + timedelta(seconds=301),UserPresence.LEGACY_STATUS_ACTIVE_INT,))@@ -1579,7 +1579,7 @@ class NormalActionsTest(BaseAction):# event status for a typical user requires settings the user's date_joined# further into the past. See test_change_presence_enabled for more details,# since it tests that codepath directly.- self.user_profile.date_joined = timezone_now() - datetime.timedelta(days=15)+ self.user_profile.date_joined = timezone_now() - timedelta(days=15)self.user_profile.save()# Set all@@ -1689,7 +1689,7 @@ class NormalActionsTest(BaseAction):# Set the date_joined for cordelia here like we did at# the start of this test.- cordelia.date_joined = timezone_now() - datetime.timedelta(days=15)+ cordelia.date_joined = timezone_now() - timedelta(days=15)cordelia.save()away_val = False@@ -2500,7 +2500,7 @@ class NormalActionsTest(BaseAction):# for backwards compatibility when dealing with a None value. Thus for this test to properly# check that the presence event emitted will have "idle" status, we need to simulate# the (more realistic) scenario where date_joined is further in the past and not super recent.- self.user_profile.date_joined = timezone_now() - datetime.timedelta(days=15)+ self.user_profile.date_joined = timezone_now() - timedelta(days=15)self.user_profile.save()for val in [True, False]:@@ -3677,7 +3677,7 @@ class RealmPropertyActionTest(BaseAction):num_events=0,)- old_datetime = timezone_now() - datetime.timedelta(days=3)+ old_datetime = timezone_now() - timedelta(days=3)old_timestamp = datetime_to_timestamp(old_datetime)now = timezone_now()timestamp_now = datetime_to_timestamp(now)diff --git a/zerver/tests/test_example.py b/zerver/tests/test_example.pyindex a657b4d16df..7387c003dd5 100644--- a/zerver/tests/test_example.py+++ b/zerver/tests/test_example.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom unittest import mockimport orjson@@ -488,7 +488,7 @@ class TestMocking(ZulipTestCase):# You can also use mock.patch() as a decorator depending on the# requirements. Read more at the documentation link provided above.- time_beyond_edit_limit = message_sent_time + datetime.timedelta(+ time_beyond_edit_limit = message_sent_time + timedelta(seconds=MESSAGE_CONTENT_EDIT_LIMIT + 100) # There's a buffer time applied to the limit, hence the extra 100s.diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex d7e520256aa..5f6e25d579b 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -1,7 +1,6 @@import calendar-import datetimeimport urllib-from datetime import timedelta+from datetime import timedelta, timezonefrom typing import TYPE_CHECKING, Any, Dictfrom unittest.mock import patch@@ -307,9 +306,7 @@ class HomeTest(ZulipTestCase):# We construct a scheduled deletion date that's definitely in# the future, regardless of how long ago the Zulip realm was# created.- realm.demo_organization_scheduled_deletion_date = timezone_now() + datetime.timedelta(- days=1- )+ realm.demo_organization_scheduled_deletion_date = timezone_now() + timedelta(days=1)realm.save()self.login("hamlet")@@ -1022,7 +1019,7 @@ class HomeTest(ZulipTestCase):# Check when server_upgrade_nag_deadline > last_server_upgrade_timehamlet = self.example_user("hamlet")iago = self.example_user("iago")- now = LAST_SERVER_UPGRADE_TIME.replace(tzinfo=datetime.timezone.utc)+ now = LAST_SERVER_UPGRADE_TIME.replace(tzinfo=timezone.utc)with time_machine.travel((now + timedelta(days=10)), tick=False):self.assertEqual(is_outdated_server(iago), False)self.assertEqual(is_outdated_server(hamlet), False)@@ -1284,7 +1281,7 @@ class HomeTest(ZulipTestCase):def test_realm_push_notifications_enabled_end_timestamp(self) -> None:self.login("hamlet")realm = get_realm("zulip")- end_timestamp = timezone_now() + datetime.timedelta(days=1)+ end_timestamp = timezone_now() + timedelta(days=1)realm.push_notifications_enabled_end_timestamp = end_timestamprealm.save()diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.pyindex 5b7c683bc70..2d769a80a31 100644--- a/zerver/tests/test_import_export.py+++ b/zerver/tests/test_import_export.py@@ -1,9 +1,9 @@-import datetimeimport jsonimport osimport shutilimport uuidfrom collections import defaultdict+from datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Set, Tuplefrom unittest.mock import patch@@ -94,8 +94,8 @@ from zerver.models import ()-def make_datetime(val: float) -> datetime.datetime:- return datetime.datetime.fromtimestamp(val, tz=datetime.timezone.utc)+def make_datetime(val: float) -> datetime:+ return datetime.fromtimestamp(val, tz=timezone.utc)def get_output_dir() -> str:@@ -832,7 +832,7 @@ class RealmImportExportTest(ExportFile):message_to=[Stream.objects.get(name="Denmark", realm=original_realm).id],topic_name="test-import",message_content="test message",- deliver_at=timezone_now() + datetime.timedelta(days=365),+ deliver_at=timezone_now() + timedelta(days=365),realm=original_realm,)original_scheduled_message = ScheduledMessage.objects.filter(realm=original_realm).last()diff --git a/zerver/tests/test_invite.py b/zerver/tests/test_invite.pyindex 7b2f25e35b3..eb0197ae926 100644--- a/zerver/tests/test_invite.py+++ b/zerver/tests/test_invite.py@@ -1,6 +1,6 @@-import datetimeimport reimport urllib+from datetime import datetime, timedeltafrom typing import TYPE_CHECKING, List, Optional, Sequence, Unionfrom unittest.mock import patchfrom urllib.parse import urlencode@@ -226,7 +226,7 @@ class InviteUserTest(InviteUserBase):result = self.invite(invitee, [stream_name])self.assert_json_success(result)- user_profile.date_joined = timezone_now() - datetime.timedelta(days=10)+ user_profile.date_joined = timezone_now() - timedelta(days=10)user_profile.save()with self.settings(INVITES_MIN_USER_AGE_DAYS=5):@@ -321,7 +321,7 @@ class InviteUserTest(InviteUserBase):# We've sent 20 invites. The realm is exempt from the new realm max# (INVITES_NEW_REALM_LIMIT_DAYS) if it is old enough- realm.date_created = timezone_now() - datetime.timedelta(days=8)+ realm.date_created = timezone_now() - timedelta(days=8)realm.save()result = try_invite(10, default_realm_max=50, new_realm_max=20, realm_max=40)self.assert_json_success(result)@@ -337,7 +337,7 @@ class InviteUserTest(InviteUserBase):# We've sent 40 invites "today". Fast-forward 48 hours# and ensure that we can invite more people- with time_machine.travel(timezone_now() + datetime.timedelta(hours=48), tick=False):+ with time_machine.travel(timezone_now() + timedelta(hours=48), tick=False):result = try_invite(5, default_realm_max=30, new_realm_max=20, realm_max=10)self.assert_json_success(result)self.check_sent_emails([f"zulip-{i:02}@zulip.com" for i in range(5)], clear=True)@@ -350,7 +350,7 @@ class InviteUserTest(InviteUserBase):# We've sent 5 invites. Reset the realm to be "recently"# created, and ensure that we can trip the whole-server# limit- realm.date_created = timezone_now() - datetime.timedelta(days=3)+ realm.date_created = timezone_now() - timedelta(days=3)realm.save()result = try_invite(10, default_realm_max=50, new_realm_max=10, realm_max=40)self.assert_json_error_contains(result, "reached the limit")@@ -444,7 +444,7 @@ class InviteUserTest(InviteUserBase):# Remove some more warning flagsdo_change_realm_subdomain(realm, "reasonable", acting_user=None)realm.description = "A real place"- realm.date_created = timezone_now() - datetime.timedelta(hours=2)+ realm.date_created = timezone_now() - timedelta(hours=2)realm.save()# This is now more allowable (5x current 2 users)@@ -895,9 +895,7 @@ class InviteUserTest(InviteUserBase):do_set_realm_property(realm, "waiting_period_threshold", 1000, acting_user=None)hamlet = self.example_user("hamlet")- hamlet.date_joined = timezone_now() - datetime.timedelta(- days=realm.waiting_period_threshold - 1- )+ hamlet.date_joined = timezone_now() - timedelta(days=realm.waiting_period_threshold - 1)email = "[email protected]"email2 = "[email protected]"@@ -1438,7 +1436,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!"prereg_user = PreregistrationUser.objects.create(email=email, referred_by=inviter, realm=realm)- date_sent = timezone_now() - datetime.timedelta(weeks=3)+ date_sent = timezone_now() - timedelta(weeks=3)with time_machine.travel(date_sent, tick=False):url = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION)@@ -1782,7 +1780,7 @@ class InvitationsTestCase(InviteUserBase):invite_expires_in_minutes=invite_expires_in_minutes,)- with time_machine.travel((timezone_now() - datetime.timedelta(days=3)), tick=False):+ with time_machine.travel((timezone_now() - timedelta(days=3)), tick=False):do_invite_users(user_profile,["[email protected]"],@@ -1825,7 +1823,7 @@ class InvitationsTestCase(InviteUserBase):get_stream(stream_name, user_profile.realm) for stream_name in ["Denmark", "Scotland"]]- with time_machine.travel((timezone_now() - datetime.timedelta(days=1000)), tick=False):+ with time_machine.travel((timezone_now() - timedelta(days=1000)), tick=False):# Testing the invitation with expiry date set to "None" exists# after a large amount of days.do_invite_users(@@ -2274,7 +2272,7 @@ class MultiuseInviteTest(ZulipTestCase):self.realm.save()def generate_multiuse_invite_link(- self, streams: Optional[List[Stream]] = None, date_sent: Optional[datetime.datetime] = None+ self, streams: Optional[List[Stream]] = None, date_sent: Optional[datetime] = None) -> str:invite = MultiuseInvite(realm=self.realm, referred_by=self.example_user("iago"))invite.save()@@ -2325,7 +2323,7 @@ class MultiuseInviteTest(ZulipTestCase):email2 = self.nonreg_email("test1")email3 = self.nonreg_email("alice")- date_sent = timezone_now() - datetime.timedelta(days=1)+ date_sent = timezone_now() - timedelta(days=1)invite_link = self.generate_multiuse_invite_link(date_sent=date_sent)self.check_user_able_to_register(email1, invite_link)@@ -2334,9 +2332,7 @@ class MultiuseInviteTest(ZulipTestCase):def test_expired_multiuse_link(self) -> None:email = self.nonreg_email("newuser")- date_sent = timezone_now() - datetime.timedelta(- days=settings.INVITATION_LINK_VALIDITY_DAYS + 1- )+ date_sent = timezone_now() - timedelta(days=settings.INVITATION_LINK_VALIDITY_DAYS + 1)invite_link = self.generate_multiuse_invite_link(date_sent=date_sent)result = self.client_post(invite_link, {"email": email})diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.pyindex 9108ece2136..c17c7a83433 100644--- a/zerver/tests/test_message_edit.py+++ b/zerver/tests/test_message_edit.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom operator import itemgetterfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Unionfrom unittest import mock@@ -1107,7 +1107,7 @@ class EditMessageTest(EditMessageTestCase):self.example_user("iago"), "Denmark", content="content", topic_name="topic")message = Message.objects.get(id=id_)- message.date_sent = message.date_sent - datetime.timedelta(seconds=180)+ message.date_sent = message.date_sent - timedelta(seconds=180)message.save()# test the various possible message editing settings@@ -1185,7 +1185,7 @@ class EditMessageTest(EditMessageTestCase):self.example_user("hamlet"), "Denmark", content="content", topic_name="topic")message = Message.objects.get(id=id_)- message.date_sent = message.date_sent - datetime.timedelta(seconds=180)+ message.date_sent = message.date_sent - timedelta(seconds=180)message.save()# Guest user must be subscribed to the stream to access the message.@@ -1210,9 +1210,9 @@ class EditMessageTest(EditMessageTestCase):hamlet = self.example_user("hamlet")do_set_realm_property(cordelia.realm, "waiting_period_threshold", 10, acting_user=None)- cordelia.date_joined = timezone_now() - datetime.timedelta(days=9)+ cordelia.date_joined = timezone_now() - timedelta(days=9)cordelia.save()- hamlet.date_joined = timezone_now() - datetime.timedelta(days=9)+ hamlet.date_joined = timezone_now() - timedelta(days=9)hamlet.save()do_edit_message_assert_error(id_, "C", "You don't have permission to edit this message", "cordelia"@@ -1223,9 +1223,9 @@ class EditMessageTest(EditMessageTestCase):id_, "C", "You don't have permission to edit this message", "hamlet")- cordelia.date_joined = timezone_now() - datetime.timedelta(days=11)+ cordelia.date_joined = timezone_now() - timedelta(days=11)cordelia.save()- hamlet.date_joined = timezone_now() - datetime.timedelta(days=11)+ hamlet.date_joined = timezone_now() - timedelta(days=11)hamlet.save()do_edit_message_assert_success(id_, "C", "cordelia")do_edit_message_assert_success(id_, "CD", "hamlet")@@ -1263,7 +1263,7 @@ class EditMessageTest(EditMessageTestCase):# non-admin users cannot edit topics sent > 1 week ago including# sender of the message.- message.date_sent = message.date_sent - datetime.timedelta(seconds=604900)+ message.date_sent = message.date_sent - timedelta(seconds=604900)message.save()set_message_editing_params(True, "unlimited", Realm.POLICY_EVERYONE)do_edit_message_assert_success(id_, "E", "iago")@@ -2749,15 +2749,15 @@ class EditMessageTest(EditMessageTestCase):)message = Message.objects.get(id=id1)- message.date_sent = message.date_sent - datetime.timedelta(days=10)+ message.date_sent = message.date_sent - timedelta(days=10)message.save()message = Message.objects.get(id=id2)- message.date_sent = message.date_sent - datetime.timedelta(days=8)+ message.date_sent = message.date_sent - timedelta(days=8)message.save()message = Message.objects.get(id=id3)- message.date_sent = message.date_sent - datetime.timedelta(days=5)+ message.date_sent = message.date_sent - timedelta(days=5)message.save()verona = get_stream("Verona", user_profile.realm)@@ -2945,19 +2945,19 @@ class EditMessageTest(EditMessageTestCase):self.send_stream_message(hamlet, "privatestream", topic_name="topic1")message = Message.objects.get(id=id1)- message.date_sent = message.date_sent - datetime.timedelta(days=10)+ message.date_sent = message.date_sent - timedelta(days=10)message.save()message = Message.objects.get(id=id2)- message.date_sent = message.date_sent - datetime.timedelta(days=9)+ message.date_sent = message.date_sent - timedelta(days=9)message.save()message = Message.objects.get(id=id3)- message.date_sent = message.date_sent - datetime.timedelta(days=8)+ message.date_sent = message.date_sent - timedelta(days=8)message.save()message = Message.objects.get(id=id4)- message.date_sent = message.date_sent - datetime.timedelta(days=6)+ message.date_sent = message.date_sent - timedelta(days=6)message.save()self.login("hamlet")@@ -3630,7 +3630,7 @@ class EditMessageTest(EditMessageTestCase):# non-admin and non-moderator users cannot move messages sent > 1 week ago# including sender of the message.message = Message.objects.get(id=msg_id)- message.date_sent = message.date_sent - datetime.timedelta(seconds=604900)+ message.date_sent = message.date_sent - timedelta(seconds=604900)message.save()check_move_message_to_stream(cordelia,@@ -4801,7 +4801,7 @@ class DeleteMessageTest(ZulipTestCase):set_message_deleting_params(Realm.POLICY_EVERYONE, "unlimited")msg_id = self.send_stream_message(hamlet, "Denmark")message = Message.objects.get(id=msg_id)- message.date_sent = message.date_sent - datetime.timedelta(seconds=600)+ message.date_sent = message.date_sent - timedelta(seconds=600)message.save()result = test_delete_message_by_other_user(msg_id=msg_id)@@ -4814,12 +4814,12 @@ class DeleteMessageTest(ZulipTestCase):set_message_deleting_params(Realm.POLICY_EVERYONE, 240)msg_id_1 = self.send_stream_message(hamlet, "Denmark")message = Message.objects.get(id=msg_id_1)- message.date_sent = message.date_sent - datetime.timedelta(seconds=120)+ message.date_sent = message.date_sent - timedelta(seconds=120)message.save()msg_id_2 = self.send_stream_message(hamlet, "Denmark")message = Message.objects.get(id=msg_id_2)- message.date_sent = message.date_sent - datetime.timedelta(seconds=360)+ message.date_sent = message.date_sent - timedelta(seconds=360)message.save()result = test_delete_message_by_other_user(msg_id=msg_id_1)@@ -4913,7 +4913,7 @@ class DeleteMessageTest(ZulipTestCase):set_message_deleting_params(Realm.POLICY_EVERYONE, 600)message = Message.objects.get(id=msg_id)- message.date_sent = timezone_now() - datetime.timedelta(seconds=700)+ message.date_sent = timezone_now() - timedelta(seconds=700)message.save()result = test_delete_message_by_other_user(msg_id)@@ -4934,13 +4934,13 @@ class DeleteMessageTest(ZulipTestCase):set_message_deleting_params(Realm.POLICY_EVERYONE, 600)message = Message.objects.get(id=msg_id)- message.date_sent = timezone_now() - datetime.timedelta(seconds=700)+ message.date_sent = timezone_now() - timedelta(seconds=700)message.save()result = self.api_delete(test_bot, f"/api/v1/messages/{msg_id}")self.assert_json_error(result, "The time limit for deleting this message has passed")- message.date_sent = timezone_now() - datetime.timedelta(seconds=400)+ message.date_sent = timezone_now() - timedelta(seconds=400)message.save()result = self.api_delete(test_bot, f"/api/v1/messages/{msg_id}")self.assert_json_success(result)@@ -4987,12 +4987,12 @@ class DeleteMessageTest(ZulipTestCase):)do_set_realm_property(realm, "waiting_period_threshold", 10, acting_user=None)cordelia = self.example_user("cordelia")- cordelia.date_joined = timezone_now() - datetime.timedelta(days=9)+ cordelia.date_joined = timezone_now() - timedelta(days=9)cordelia.save()check_delete_message_by_sender("cordelia", "You don't have permission to delete this message")- cordelia.date_joined = timezone_now() - datetime.timedelta(days=11)+ cordelia.date_joined = timezone_now() - timedelta(days=11)cordelia.save()check_delete_message_by_sender("cordelia")diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex e08d4472d6d..d0af580e851 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Unionfrom unittest import mock@@ -4451,7 +4451,7 @@ class MessageVisibilityTest(ZulipTestCase):realm.message_visibility_limit = Nonerealm.save()- end_time = timezone_now() - datetime.timedelta(hours=lookback_hours - 5)+ end_time = timezone_now() - timedelta(hours=lookback_hours - 5)stat = COUNT_STATS["messages_sent:is_bot:hour"]RealmCount.objects.create(realm=realm, property=stat.property, end_time=end_time, value=5)diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex e47128a28a9..d79057191a9 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom email.headerregistry import Addressfrom typing import Any, Optional, Setfrom unittest import mock@@ -411,7 +411,7 @@ class MessagePOSTTest(ZulipTestCase):self.login_user(admin_profile)do_set_realm_property(admin_profile.realm, "waiting_period_threshold", 10, acting_user=None)- admin_profile.date_joined = timezone_now() - datetime.timedelta(days=9)+ admin_profile.date_joined = timezone_now() - timedelta(days=9)admin_profile.save()self.assertTrue(admin_profile.is_provisional_member)self.assertTrue(admin_profile.is_realm_admin)@@ -435,7 +435,7 @@ class MessagePOSTTest(ZulipTestCase):non_admin_profile = self.example_user("hamlet")self.login_user(non_admin_profile)- non_admin_profile.date_joined = timezone_now() - datetime.timedelta(days=9)+ non_admin_profile.date_joined = timezone_now() - timedelta(days=9)non_admin_profile.save()self.assertTrue(non_admin_profile.is_provisional_member)self.assertFalse(non_admin_profile.is_realm_admin)@@ -454,7 +454,7 @@ class MessagePOSTTest(ZulipTestCase):non_admin_owned_bot, stream_name, "New members cannot send to this stream.")- non_admin_profile.date_joined = timezone_now() - datetime.timedelta(days=11)+ non_admin_profile.date_joined = timezone_now() - timedelta(days=11)non_admin_profile.save()self.assertFalse(non_admin_profile.is_provisional_member)@@ -479,7 +479,7 @@ class MessagePOSTTest(ZulipTestCase):)moderator_profile = self.example_user("shiva")- moderator_profile.date_joined = timezone_now() - datetime.timedelta(days=9)+ moderator_profile.date_joined = timezone_now() - timedelta(days=9)moderator_profile.save()self.assertTrue(moderator_profile.is_moderator)self.assertFalse(moderator_profile.is_provisional_member)@@ -492,7 +492,7 @@ class MessagePOSTTest(ZulipTestCase):full_name="whatever3",user_profile=moderator_profile,)- moderator_owned_bot.date_joined = timezone_now() - datetime.timedelta(days=11)+ moderator_owned_bot.date_joined = timezone_now() - timedelta(days=11)moderator_owned_bot.save()self._send_and_verify_message(moderator_owned_bot, stream_name)@@ -1275,7 +1275,7 @@ class MessagePOSTTest(ZulipTestCase):self.subscribe(user, "IRCland")# Simulate a mirrored message with a slightly old timestamp.- fake_date_sent = timezone_now() - datetime.timedelta(minutes=37)+ fake_date_sent = timezone_now() - timedelta(minutes=37)fake_timestamp = datetime_to_timestamp(fake_date_sent)result = self.api_post(@@ -1298,7 +1298,7 @@ class MessagePOSTTest(ZulipTestCase):self.assertEqual(int(datetime_to_timestamp(msg.date_sent)), int(fake_timestamp))# Now test again using forged=yes- fake_date_sent = timezone_now() - datetime.timedelta(minutes=22)+ fake_date_sent = timezone_now() - timedelta(minutes=22)fake_timestamp = datetime_to_timestamp(fake_date_sent)result = self.api_post(@@ -1854,7 +1854,7 @@ class StreamMessagesTest(ZulipTestCase):self.send_and_verify_topic_wildcard_mention_message("iago")self.send_and_verify_topic_wildcard_mention_message("shiva")- cordelia.date_joined = timezone_now() - datetime.timedelta(days=11)+ cordelia.date_joined = timezone_now() - timedelta(days=11)cordelia.save()self.send_and_verify_topic_wildcard_mention_message("cordelia")@@ -1953,7 +1953,7 @@ class StreamMessagesTest(ZulipTestCase):self.send_and_verify_stream_wildcard_mention_message("iago")self.send_and_verify_stream_wildcard_mention_message("shiva")- cordelia.date_joined = timezone_now() - datetime.timedelta(days=11)+ cordelia.date_joined = timezone_now() - timedelta(days=11)cordelia.save()self.send_and_verify_stream_wildcard_mention_message("cordelia")@@ -2904,7 +2904,7 @@ class CheckMessageTest(ZulipTestCase):# after; this should send an error to the bot owner that the# stream doesn't existassert sender.last_reminder is not None- sender.last_reminder = sender.last_reminder - datetime.timedelta(hours=1)+ sender.last_reminder = sender.last_reminder - timedelta(hours=1)sender.save(update_fields=["last_reminder"])ret = check_message(sender, client, addressee, message_content)diff --git a/zerver/tests/test_messages.py b/zerver/tests/test_messages.pyindex 70278bb754a..2fb797158cf 100644--- a/zerver/tests/test_messages.py+++ b/zerver/tests/test_messages.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom typing import Listfrom django.utils.timezone import now as timezone_now@@ -38,7 +38,7 @@ class MissedMessageTest(ZulipTestCase):self.assertEqual(sorted(user_ids), sorted(presence_idle_user_ids))def set_presence(user: UserProfile, client_name: str, ago: int) -> None:- when = timezone_now() - datetime.timedelta(seconds=ago)+ when = timezone_now() - timedelta(seconds=ago)UserPresence.objects.update_or_create(user_profile_id=user.id,defaults=dict(diff --git a/zerver/tests/test_new_users.py b/zerver/tests/test_new_users.pyindex 2b8096cdeb7..cb2e392fc2e 100644--- a/zerver/tests/test_new_users.py+++ b/zerver/tests/test_new_users.py@@ -1,5 +1,5 @@-import datetimeimport sys+from datetime import datetime, timedelta, timezonefrom typing import Sequenceimport time_machine@@ -37,12 +37,12 @@ class SendLoginEmailTest(ZulipTestCase):with self.settings(SEND_LOGIN_EMAILS=True):self.assertTrue(settings.SEND_LOGIN_EMAILS)# we don't use the self.login method since we spoof the user-agent- mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=datetime.timezone.utc)+ mock_time = datetime(year=2018, month=1, day=1, tzinfo=timezone.utc)user = self.example_user("hamlet")user.timezone = "US/Pacific"user.twenty_four_hour_time = False- user.date_joined = mock_time - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1)+ user.date_joined = mock_time - timedelta(seconds=JUST_CREATED_THRESHOLD + 1)user.save()password = initial_password(user.delivery_email)login_info = dict(@@ -53,7 +53,7 @@ class SendLoginEmailTest(ZulipTestCase):"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")user_tz = zoneinfo.ZoneInfo(user.timezone)- mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=datetime.timezone.utc)+ mock_time = datetime(year=2018, month=1, day=1, tzinfo=timezone.utc)reference_time = mock_time.astimezone(user_tz).strftime("%A, %B %d, %Y at %I:%M %p %Z")with time_machine.travel(mock_time, tick=False):self.client_post(@@ -108,10 +108,10 @@ class SendLoginEmailTest(ZulipTestCase):@override_settings(SEND_LOGIN_EMAILS=True)def test_enable_login_emails_user_setting(self) -> None:user = self.example_user("hamlet")- mock_time = datetime.datetime(year=2018, month=1, day=1, tzinfo=datetime.timezone.utc)+ mock_time = datetime(year=2018, month=1, day=1, tzinfo=timezone.utc)user.timezone = "US/Pacific"- user.date_joined = mock_time - datetime.timedelta(seconds=JUST_CREATED_THRESHOLD + 1)+ user.date_joined = mock_time - timedelta(seconds=JUST_CREATED_THRESHOLD + 1)user.save()do_change_user_setting(user, "enable_login_emails", False, acting_user=None)diff --git a/zerver/tests/test_presence.py b/zerver/tests/test_presence.pyindex cc74f6b87a3..cfbee31d56d 100644--- a/zerver/tests/test_presence.py+++ b/zerver/tests/test_presence.py@@ -1,5 +1,4 @@-import datetime-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Any, Dictfrom unittest import mock@@ -58,7 +57,7 @@ class UserPresenceModelTests(ZulipTestCase):def back_date(num_weeks: int) -> None:user_presence = UserPresence.objects.get(user_profile=user_profile)- backdated_timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks)+ backdated_timestamp = timezone_now() - timedelta(weeks=num_weeks)user_presence.last_active_time = backdated_timestampuser_presence.last_connected_time = backdated_timestampuser_presence.save()@@ -527,24 +526,24 @@ class SingleUserPresenceTests(ZulipTestCase):class UserPresenceAggregationTests(ZulipTestCase):def _send_presence_for_aggregated_tests(- self, user: UserProfile, status: str, validate_time: datetime.datetime+ self, user: UserProfile, status: str, validate_time: datetime) -> Dict[str, Dict[str, Any]]:self.login_user(user)# First create some initial, old presence to avoid the details of the edge case of initial# presence creation messing with the intended setup.- with time_machine.travel((validate_time - datetime.timedelta(days=365)), tick=False):+ with time_machine.travel((validate_time - timedelta(days=365)), tick=False):self.client_post("/json/users/me/presence", {"status": status})- with time_machine.travel((validate_time - datetime.timedelta(seconds=5)), tick=False):+ with time_machine.travel((validate_time - timedelta(seconds=5)), tick=False):self.client_post("/json/users/me/presence", {"status": status})- with time_machine.travel((validate_time - datetime.timedelta(seconds=2)), tick=False):+ with time_machine.travel((validate_time - timedelta(seconds=2)), tick=False):self.api_post(user,"/api/v1/users/me/presence",{"status": status},HTTP_USER_AGENT="ZulipAndroid/1.0",)- with time_machine.travel((validate_time - datetime.timedelta(seconds=7)), tick=False):+ with time_machine.travel((validate_time - timedelta(seconds=7)), tick=False):latest_result = self.api_post(user,"/api/v1/users/me/presence",@@ -556,7 +555,7 @@ class UserPresenceAggregationTests(ZulipTestCase):latest_result_dict["presences"][user.email]["aggregated"],{"status": status,- "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=5)),+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),# We no longer store the client information, but keep the field in these dicts,# with the value 'website' for backwards compatibility."client": "website",@@ -568,7 +567,7 @@ class UserPresenceAggregationTests(ZulipTestCase):def test_aggregated_info(self) -> None:user = self.example_user("othello")- offset = datetime.timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS + 1)+ offset = timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS + 1)validate_time = timezone_now() - offsetself._send_presence_for_aggregated_tests(user, "active", validate_time)with time_machine.travel((validate_time + offset), tick=False):@@ -596,7 +595,7 @@ class UserPresenceAggregationTests(ZulipTestCase):result_dict["presence"]["aggregated"],{"status": "active",- "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=5)),+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),},)@@ -608,7 +607,7 @@ class UserPresenceAggregationTests(ZulipTestCase):result_dict["presence"]["aggregated"],{"status": "idle",- "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=5)),+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),},)@@ -617,7 +616,7 @@ class UserPresenceAggregationTests(ZulipTestCase):self.login_user(user)validate_time = timezone_now()self._send_presence_for_aggregated_tests(user, "idle", validate_time)- with time_machine.travel((validate_time - datetime.timedelta(seconds=3)), tick=False):+ with time_machine.travel((validate_time - timedelta(seconds=3)), tick=False):result_dict = self.api_post(user,"/api/v1/users/me/presence",@@ -630,7 +629,7 @@ class UserPresenceAggregationTests(ZulipTestCase):{"client": "website","status": "active",- "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=3)),+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=3)),},)@@ -641,7 +640,7 @@ class UserPresenceAggregationTests(ZulipTestCase):result_dict = self._send_presence_for_aggregated_tests(user, "idle", validate_time)with time_machine.travel(- (validate_time + datetime.timedelta(seconds=settings.OFFLINE_THRESHOLD_SECS + 1)),+ (validate_time + timedelta(seconds=settings.OFFLINE_THRESHOLD_SECS + 1)),tick=False,):# After settings.OFFLINE_THRESHOLD_SECS + 1 this generated, recent presence data@@ -653,7 +652,7 @@ class UserPresenceAggregationTests(ZulipTestCase):result_dict["presence"]["aggregated"],{"status": "offline",- "timestamp": datetime_to_timestamp(validate_time - datetime.timedelta(seconds=5)),+ "timestamp": datetime_to_timestamp(validate_time - timedelta(seconds=5)),},)diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.pyindex 90be822478d..6c7e3304034 100644--- a/zerver/tests/test_push_notifications.py+++ b/zerver/tests/test_push_notifications.py@@ -1,8 +1,8 @@import asyncioimport base64-import datetimeimport uuidfrom contextlib import contextmanager+from datetime import datetime, timedelta, timezonefrom typing import Any, Dict, Iterator, List, Mapping, Optional, Tuple, Unionfrom unittest import mock, skipUnless@@ -684,7 +684,7 @@ class PushBouncerNotificationTest(BouncerTestCase):"apns_payload": apns_payload,"gcm_options": gcm_options,}- time_received = time_sent + datetime.timedelta(seconds=1, milliseconds=234)+ time_received = time_sent + timedelta(seconds=1, milliseconds=234)with time_machine.travel(time_received, tick=False), mock.patch("zilencer.views.send_android_push_notification", return_value=1), mock.patch(@@ -1009,7 +1009,7 @@ class PushBouncerNotificationTest(BouncerTestCase):class AnalyticsBouncerTest(BouncerTestCase):- TIME_ZERO = datetime.datetime(1988, 3, 14, tzinfo=datetime.timezone.utc)+ TIME_ZERO = datetime(1988, 3, 14, tzinfo=timezone.utc)@override_settings(PUSH_NOTIFICATION_BOUNCER_URL="https://push.zulip.org.example.com")@responses.activate@@ -1277,13 +1277,13 @@ class AnalyticsBouncerTest(BouncerTestCase):RealmCount.objects.create(realm=user.realm,property=realm_stat.property,- end_time=end_time + datetime.timedelta(days=1),+ end_time=end_time + timedelta(days=1),value=6,)RealmCount.objects.create(realm=user.realm,property=realm_stat.property,- end_time=end_time + datetime.timedelta(days=2),+ end_time=end_time + timedelta(days=2),value=9,)send_analytics_to_push_bouncer()@@ -1291,7 +1291,7 @@ class AnalyticsBouncerTest(BouncerTestCase):# Test only having new InstallationCount rowsInstallationCount.objects.create(- property=realm_stat.property, end_time=end_time + datetime.timedelta(days=1), value=6+ property=realm_stat.property, end_time=end_time + timedelta(days=1), value=6)send_analytics_to_push_bouncer()check_counts(7, 7, 3, 2, 7)@@ -1659,7 +1659,7 @@ class AnalyticsBouncerTest(BouncerTestCase):dummy_customer_plan = mock.MagicMock()dummy_customer_plan.status = CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE- dummy_date = datetime.datetime(year=2023, month=12, day=3, tzinfo=datetime.timezone.utc)+ dummy_date = datetime(year=2023, month=12, day=3, tzinfo=timezone.utc)with mock.patch("zilencer.views.RemoteRealmBillingSession.get_customer", return_value=dummy_customer):@@ -1881,7 +1881,7 @@ class HandlePushNotificationTest(PushNotificationTest):message=message,)- time_received = time_sent + datetime.timedelta(seconds=1, milliseconds=234)+ time_received = time_sent + timedelta(seconds=1, milliseconds=234)missed_message = {"message_id": message.id,"trigger": NotificationTriggers.DIRECT_MESSAGE,@@ -1968,7 +1968,7 @@ class HandlePushNotificationTest(PushNotificationTest):message=message,)- time_received = time_sent + datetime.timedelta(seconds=1, milliseconds=234)+ time_received = time_sent + timedelta(seconds=1, milliseconds=234)missed_message = {"message_id": message.id,"trigger": NotificationTriggers.DIRECT_MESSAGE,diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.pyindex 28870715804..c0a90309d27 100644--- a/zerver/tests/test_queue_worker.py+++ b/zerver/tests/test_queue_worker.py@@ -1,11 +1,11 @@import base64-import datetimeimport itertoolsimport osimport signalimport timefrom collections import defaultdictfrom contextlib import contextmanager, suppress+from datetime import datetime, timedelta, timezonefrom inspect import isabstractfrom typing import Any, Callable, Dict, Iterator, List, Mapping, Optionalfrom unittest.mock import MagicMock, patch@@ -161,9 +161,7 @@ class WorkerTest(ZulipTestCase):events = [hamlet_event1, hamlet_event2, othello_event]mmw = MissedMessageWorker()- batch_duration = datetime.timedelta(- seconds=hamlet.email_notifications_batching_period_seconds- )+ batch_duration = timedelta(seconds=hamlet.email_notifications_batching_period_seconds)assert (hamlet.email_notifications_batching_period_seconds== othello.email_notifications_batching_period_seconds@@ -181,7 +179,7 @@ class WorkerTest(ZulipTestCase):def check_row(row: ScheduledMessageNotificationEmail,- scheduled_timestamp: datetime.datetime,+ scheduled_timestamp: datetime,mentioned_user_group_id: Optional[int],) -> None:self.assertEqual(row.trigger, NotificationTriggers.DIRECT_MESSAGE)@@ -213,7 +211,7 @@ class WorkerTest(ZulipTestCase):self.assertFalse(has_timeout)# Enqueues the events to the internal queue, as if from RabbitMQ- time_zero = datetime.datetime(2021, 1, 1, tzinfo=datetime.timezone.utc)+ time_zero = datetime(2021, 1, 1, tzinfo=timezone.utc)with time_machine.travel(time_zero, tick=False), patch.object(mmw.cv, "notify") as notify_mock:@@ -252,7 +250,7 @@ class WorkerTest(ZulipTestCase):# If another event is received, test that it gets saved with the same# `expected_scheduled_timestamp` as the earlier events.- few_moments_later = time_zero + datetime.timedelta(seconds=3)+ few_moments_later = time_zero + timedelta(seconds=3)with time_machine.travel(few_moments_later, tick=False), patch.object(mmw.cv, "notify") as notify_mock:@@ -269,14 +267,14 @@ class WorkerTest(ZulipTestCase):# Now let us test `maybe_send_batched_emails`# If called too early, it shouldn't process the emails.- one_minute_premature = expected_scheduled_timestamp - datetime.timedelta(seconds=60)+ one_minute_premature = expected_scheduled_timestamp - timedelta(seconds=60)with time_machine.travel(one_minute_premature, tick=False):has_timeout = advance()self.assertTrue(has_timeout)self.assertEqual(ScheduledMessageNotificationEmail.objects.count(), 4)# If called after `expected_scheduled_timestamp`, it should process all emails.- one_minute_overdue = expected_scheduled_timestamp + datetime.timedelta(seconds=60)+ one_minute_overdue = expected_scheduled_timestamp + timedelta(seconds=60)with time_machine.travel(one_minute_overdue, tick=True):with send_mock as sm, self.assertLogs(level="INFO") as info_logs:has_timeout = advance()@@ -342,7 +340,7 @@ class WorkerTest(ZulipTestCase):# Verify that we make forward progress if one of the messages# throws an exception. First, enqueue the messages, and get# them to create database rows:- time_zero = datetime.datetime(2021, 1, 1, tzinfo=datetime.timezone.utc)+ time_zero = datetime(2021, 1, 1, tzinfo=timezone.utc)with time_machine.travel(time_zero, tick=False), patch.object(mmw.cv, "notify") as notify_mock:@@ -359,7 +357,7 @@ class WorkerTest(ZulipTestCase):if user.id == hamlet.id:raise RuntimeError- one_minute_overdue = expected_scheduled_timestamp + datetime.timedelta(seconds=60)+ one_minute_overdue = expected_scheduled_timestamp + timedelta(seconds=60)with time_machine.travel(one_minute_overdue, tick=False), self.assertLogs(level="ERROR") as error_logs, send_mock as sm:diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.pyindex 04e444f36cb..82f132900a5 100644--- a/zerver/tests/test_realm.py+++ b/zerver/tests/test_realm.py@@ -1,8 +1,7 @@-import datetimeimport jsonimport osimport re-from datetime import timedelta+from datetime import datetime, timedeltafrom typing import Any, Dict, List, Unionfrom unittest import mock@@ -226,9 +225,7 @@ class RealmTest(ZulipTestCase):data = dict(string_id="lear")self.login("desdemona")realm = get_realm("zulip")- realm.demo_organization_scheduled_deletion_date = timezone_now() + datetime.timedelta(- days=30- )+ realm.demo_organization_scheduled_deletion_date = timezone_now() + timedelta(days=30)realm.save()result = self.client_patch("/json/realm", data)self.assert_json_error(result, "Subdomain already in use. Please choose a different one.")@@ -334,7 +331,7 @@ class RealmTest(ZulipTestCase):"zerver/emails/onboarding_zulip_topics",user.realm,to_user_ids=[user.id],- delay=datetime.timedelta(hours=1),+ delay=timedelta(hours=1),)self.assertEqual(ScheduledEmail.objects.count(), 1)do_deactivate_realm(user.realm, acting_user=None)@@ -933,7 +930,7 @@ class RealmTest(ZulipTestCase):self.assertTrue(realm.invite_required)self.assertEqual(realm.plan_type, Realm.PLAN_TYPE_LIMITED)self.assertEqual(realm.org_type, Realm.ORG_TYPES["unspecified"]["id"])- self.assertEqual(type(realm.date_created), datetime.datetime)+ self.assertEqual(type(realm.date_created), datetime)self.assertTrue(RealmAuditLog.objects.filter(@@ -960,7 +957,7 @@ class RealmTest(ZulipTestCase):)def test_do_create_realm_with_keyword_arguments(self) -> None:- date_created = timezone_now() - datetime.timedelta(days=100)+ date_created = timezone_now() - timedelta(days=100)realm = do_create_realm("realm_string_id","realm name",diff --git a/zerver/tests/test_scheduled_messages.py b/zerver/tests/test_scheduled_messages.pyindex a8cb6008b85..5804cd17ed8 100644--- a/zerver/tests/test_scheduled_messages.py+++ b/zerver/tests/test_scheduled_messages.py@@ -1,6 +1,6 @@-import datetimeimport reimport time+from datetime import timedeltafrom io import StringIOfrom typing import TYPE_CHECKING, Any, Dict, List, Unionfrom unittest import mock@@ -95,7 +95,7 @@ class ScheduledMessageTest(ZulipTestCase):def create_scheduled_message(self) -> None:content = "Test message"- scheduled_delivery_datetime = timezone_now() + datetime.timedelta(minutes=5)+ scheduled_delivery_datetime = timezone_now() + timedelta(minutes=5)scheduled_delivery_timestamp = int(scheduled_delivery_datetime.timestamp())verona_stream_id = self.get_stream_id("Verona")result = self.do_schedule_message(@@ -113,8 +113,8 @@ class ScheduledMessageTest(ZulipTestCase):scheduled_message = self.last_scheduled_message()# mock current time to be greater than the scheduled time, so that the `scheduled_message` can be sent.- more_than_scheduled_delivery_datetime = (- scheduled_message.scheduled_timestamp + datetime.timedelta(minutes=1)+ more_than_scheduled_delivery_datetime = scheduled_message.scheduled_timestamp + timedelta(+ minutes=1)with time_machine.travel(more_than_scheduled_delivery_datetime, tick=False):@@ -142,7 +142,7 @@ class ScheduledMessageTest(ZulipTestCase):self.assertFalse(try_deliver_one_scheduled_message(logger))content = "Test message"- scheduled_delivery_datetime = timezone_now() + datetime.timedelta(minutes=5)+ scheduled_delivery_datetime = timezone_now() + timedelta(minutes=5)scheduled_delivery_timestamp = int(scheduled_delivery_datetime.timestamp())sender = self.example_user("hamlet")othello = self.example_user("othello")@@ -153,9 +153,7 @@ class ScheduledMessageTest(ZulipTestCase):scheduled_message = self.last_scheduled_message()# mock current time to be greater than the scheduled time.- more_than_scheduled_delivery_datetime = scheduled_delivery_datetime + datetime.timedelta(- minutes=1- )+ more_than_scheduled_delivery_datetime = scheduled_delivery_datetime + timedelta(minutes=1)with time_machine.travel(more_than_scheduled_delivery_datetime, tick=False):result = try_deliver_one_scheduled_message(logger)@@ -181,7 +179,7 @@ class ScheduledMessageTest(ZulipTestCase):# Check error is sent if an edit happens after the scheduled# message is successfully sent.- new_delivery_datetime = timezone_now() + datetime.timedelta(minutes=7)+ new_delivery_datetime = timezone_now() + timedelta(minutes=7)new_delivery_timestamp = int(new_delivery_datetime.timestamp())content = "New message content"payload = {@@ -199,7 +197,7 @@ class ScheduledMessageTest(ZulipTestCase):self.assertFalse(try_deliver_one_scheduled_message(logger))content = "Test message to self"- scheduled_delivery_datetime = timezone_now() + datetime.timedelta(minutes=5)+ scheduled_delivery_datetime = timezone_now() + timedelta(minutes=5)scheduled_delivery_timestamp = int(scheduled_delivery_datetime.timestamp())sender = self.example_user("hamlet")response = self.do_schedule_message(@@ -209,9 +207,7 @@ class ScheduledMessageTest(ZulipTestCase):scheduled_message = self.last_scheduled_message()# mock current time to be greater than the scheduled time.- more_than_scheduled_delivery_datetime = scheduled_delivery_datetime + datetime.timedelta(- minutes=1- )+ more_than_scheduled_delivery_datetime = scheduled_delivery_datetime + timedelta(minutes=1)with time_machine.travel(more_than_scheduled_delivery_datetime, tick=False):result = try_deliver_one_scheduled_message(logger)@@ -261,9 +257,8 @@ class ScheduledMessageTest(ZulipTestCase):self.create_scheduled_message()scheduled_message = self.last_scheduled_message()- too_late_to_send_message_datetime = (- scheduled_message.scheduled_timestamp- + datetime.timedelta(minutes=SCHEDULED_MESSAGE_LATE_CUTOFF_MINUTES + 1)+ too_late_to_send_message_datetime = scheduled_message.scheduled_timestamp + timedelta(+ minutes=SCHEDULED_MESSAGE_LATE_CUTOFF_MINUTES + 1)with time_machine.travel(too_late_to_send_message_datetime, tick=False):@@ -290,8 +285,8 @@ class ScheduledMessageTest(ZulipTestCase):self.assertFalse(scheduled_message.realm.deactivated)message_before_deactivation = most_recent_message(scheduled_message.sender)- more_than_scheduled_delivery_datetime = (- scheduled_message.scheduled_timestamp + datetime.timedelta(minutes=1)+ more_than_scheduled_delivery_datetime = scheduled_message.scheduled_timestamp + timedelta(+ minutes=1)with time_machine.travel(more_than_scheduled_delivery_datetime, tick=False):@@ -319,8 +314,8 @@ class ScheduledMessageTest(ZulipTestCase):self.assertTrue(scheduled_message.sender.is_active)message_before_deactivation = most_recent_message(scheduled_message.sender)- more_than_scheduled_delivery_datetime = (- scheduled_message.scheduled_timestamp + datetime.timedelta(minutes=1)+ more_than_scheduled_delivery_datetime = scheduled_message.scheduled_timestamp + timedelta(+ minutes=1)with time_machine.travel(more_than_scheduled_delivery_datetime, tick=False):@@ -343,8 +338,8 @@ class ScheduledMessageTest(ZulipTestCase):self.create_scheduled_message()scheduled_message = self.last_scheduled_message()- more_than_scheduled_delivery_datetime = (- scheduled_message.scheduled_timestamp + datetime.timedelta(minutes=1)+ more_than_scheduled_delivery_datetime = scheduled_message.scheduled_timestamp + timedelta(+ minutes=1)with time_machine.travel(more_than_scheduled_delivery_datetime, tick=False):@@ -382,9 +377,8 @@ class ScheduledMessageTest(ZulipTestCase):self.create_scheduled_message()scheduled_message = self.last_scheduled_message()- too_late_to_send_message_datetime = (- scheduled_message.scheduled_timestamp- + datetime.timedelta(minutes=SCHEDULED_MESSAGE_LATE_CUTOFF_MINUTES + 1)+ too_late_to_send_message_datetime = scheduled_message.scheduled_timestamp + timedelta(+ minutes=SCHEDULED_MESSAGE_LATE_CUTOFF_MINUTES + 1)with time_machine.travel(too_late_to_send_message_datetime, tick=False):@@ -403,7 +397,7 @@ class ScheduledMessageTest(ZulipTestCase):# Editing the scheduled message with that ID for a future time is# successful and resets the `failed` and `failure_message` fields.- new_delivery_datetime = timezone_now() + datetime.timedelta(minutes=60)+ new_delivery_datetime = timezone_now() + timedelta(minutes=60)new_delivery_timestamp = int(new_delivery_datetime.timestamp())scheduled_message_id = scheduled_message.idpayload_with_timestamp = {diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex 99722d8d126..61f56da3f45 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -1,7 +1,7 @@-import datetimeimport reimport timeimport urllib+from datetime import timedeltafrom typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Unionfrom unittest.mock import MagicMock, patchfrom urllib.parse import urlencode@@ -4093,7 +4093,7 @@ class UserSignUpTest(ZulipTestCase):user_profile.email_address_visibility, UserProfile.EMAIL_ADDRESS_VISIBILITY_NOBODY)- expected_deletion_date = realm.date_created + datetime.timedelta(+ expected_deletion_date = realm.date_created + timedelta(days=settings.DEMO_ORG_DEADLINE_DAYS)self.assertEqual(realm.demo_organization_scheduled_deletion_date, expected_deletion_date)diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex 2581492e7d5..c74c58afbfe 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom email.headerregistry import Addressfrom typing import Any, Dict, Iterable, List, Optional, TypeVar, Unionfrom unittest import mock@@ -1803,7 +1803,7 @@ class ActivateTest(ZulipTestCase):"zerver/emails/onboarding_zulip_topics",user.realm,to_user_ids=[user.id],- delay=datetime.timedelta(hours=1),+ delay=timedelta(hours=1),)self.assertEqual(ScheduledEmail.objects.count(), 1)do_deactivate_user(user, acting_user=None)@@ -1816,7 +1816,7 @@ class ActivateTest(ZulipTestCase):"zerver/emails/onboarding_zulip_topics",iago.realm,to_user_ids=[hamlet.id, iago.id],- delay=datetime.timedelta(hours=1),+ delay=timedelta(hours=1),)self.assertEqual(ScheduledEmail.objects.filter(users__in=[hamlet, iago]).distinct().count(), 1@@ -1832,7 +1832,7 @@ class ActivateTest(ZulipTestCase):"zerver/emails/onboarding_zulip_topics",iago.realm,to_user_ids=[hamlet.id, iago.id],- delay=datetime.timedelta(hours=1),+ delay=timedelta(hours=1),)self.assertEqual(ScheduledEmail.objects.count(), 1)clear_scheduled_emails(hamlet.id)@@ -1847,7 +1847,7 @@ class ActivateTest(ZulipTestCase):"zerver/emails/onboarding_zulip_topics",iago.realm,to_user_ids=[hamlet.id, iago.id],- delay=datetime.timedelta(hours=1),+ delay=timedelta(hours=1),)self.assertEqual(ScheduledEmail.objects.count(), 1)email = ScheduledEmail.objects.all().first()@@ -1873,7 +1873,7 @@ class ActivateTest(ZulipTestCase):"zerver/emails/onboarding_zulip_topics",iago.realm,to_user_ids=to_user_ids,- delay=datetime.timedelta(hours=1),+ delay=timedelta(hours=1),)self.assertEqual(ScheduledEmail.objects.count(), 1)email = ScheduledEmail.objects.all().first()diff --git a/zerver/views/message_edit.py b/zerver/views/message_edit.pyindex 1207a891881..de9a8c1786b 100644--- a/zerver/views/message_edit.py+++ b/zerver/views/message_edit.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom typing import List, Literal, Optional, Unionimport orjson@@ -157,7 +157,7 @@ def validate_can_delete_message(user_profile: UserProfile, message: Message) ->if deadline_seconds is None:# None means no time limit to delete messagereturn- if (timezone_now() - message.date_sent) > datetime.timedelta(seconds=deadline_seconds):+ if (timezone_now() - message.date_sent) > timedelta(seconds=deadline_seconds):# User cannot delete message after deadline time of realmraise JsonableError(_("The time limit for deleting this message has passed"))returndiff --git a/zerver/views/presence.py b/zerver/views/presence.pyindex 2cfc5d7a321..651152950d7 100644--- a/zerver/views/presence.py+++ b/zerver/views/presence.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom typing import Any, Dict, Optionalfrom django.conf import settings@@ -175,7 +175,7 @@ def update_active_status_backend(user_profile=user_profile, query="get_events", client__name="zephyr_mirror")- ret["zephyr_mirror_active"] = activity.last_visit > timezone_now() - datetime.timedelta(+ ret["zephyr_mirror_active"] = activity.last_visit > timezone_now() - timedelta(minutes=5)except UserActivity.DoesNotExist:diff --git a/zerver/views/user_topics.py b/zerver/views/user_topics.pyindex 547f93c870c..640b2c098ac 100644--- a/zerver/views/user_topics.py+++ b/zerver/views/user_topics.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetimefrom typing import Optionalfrom django.http import HttpRequest, HttpResponse@@ -24,7 +24,7 @@ def mute_topic(stream_id: Optional[int],stream_name: Optional[str],topic_name: str,- date_muted: datetime.datetime,+ date_muted: datetime,) -> None:if stream_name is not None:(stream, sub) = access_stream_by_name(user_profile, stream_name)diff --git a/zerver/worker/queue_processors.py b/zerver/worker/queue_processors.pyindex 01372543864..99136991ba7 100644--- a/zerver/worker/queue_processors.py+++ b/zerver/worker/queue_processors.py@@ -1,7 +1,6 @@# Documented in https://zulip.readthedocs.io/en/latest/subsystems/queuing.htmlimport base64import copy-import datetimeimport emailimport email.policyimport logging@@ -14,6 +13,7 @@ import timeimport urllibfrom abc import ABC, abstractmethodfrom collections import defaultdict, deque+from datetime import timedeltafrom email.message import EmailMessagefrom functools import wrapsfrom types import FrameType@@ -496,7 +496,7 @@ class ConfirmationEmailWorker(QueueProcessingWorker):from_address=FromAddress.tokenized_no_reply_placeholder,language=email_language,context=context,- delay=datetime.timedelta(minutes=invite_expires_in_minutes - (2 * 24 * 60)),+ delay=timedelta(minutes=invite_expires_in_minutes - (2 * 24 * 60)),)@@ -608,7 +608,7 @@ class MissedMessageWorker(QueueProcessingWorker):user_profile_id: int = event["user_profile_id"]user_profile = get_user_profile_by_id(user_profile_id)batch_duration_seconds = user_profile.email_notifications_batching_period_seconds- batch_duration = datetime.timedelta(seconds=batch_duration_seconds)+ batch_duration = timedelta(seconds=batch_duration_seconds)try:pending_email = ScheduledMessageNotificationEmail.objects.filter(diff --git a/zilencer/lib/remote_counts.py b/zilencer/lib/remote_counts.pyindex 4ba27b49c62..331a7381299 100644--- a/zilencer/lib/remote_counts.py+++ b/zilencer/lib/remote_counts.py@@ -1,4 +1,4 @@-import datetime+from datetime import timedeltafrom django.db import connectionfrom django.utils.timezone import now as timezone_now@@ -24,7 +24,7 @@ def compute_max_monthly_messages(remote_server: RemoteZulipServer) -> int:if not RemoteInstallationCount.objects.filter(server=remote_server,property="active_users_audit:is_bot:day",- end_time__lte=timezone_now() - datetime.timedelta(days=3),+ end_time__lte=timezone_now() - timedelta(days=3),).exists():raise MissingDataErrordiff --git a/zilencer/management/commands/add_server_to_legacy_plan.py b/zilencer/management/commands/add_server_to_legacy_plan.pyindex 62b8f539a21..96015ffcd55 100644--- a/zilencer/management/commands/add_server_to_legacy_plan.py+++ b/zilencer/management/commands/add_server_to_legacy_plan.py@@ -1,4 +1,4 @@-import datetime+from datetime import datetime, timezonefrom typing import Anyfrom django.core.management.base import BaseCommand, CommandParser@@ -38,17 +38,15 @@ class Command(BaseCommand):if renewal_date_str is None:renewal_date = timezone_now()else:- renewal_date = datetime.datetime.strptime(renewal_date_str, TIMESTAMP_FORMAT).replace(- tzinfo=datetime.timezone.utc+ renewal_date = datetime.strptime(renewal_date_str, TIMESTAMP_FORMAT).replace(+ tzinfo=timezone.utc)end_date_str = options.get("end_date")if end_date_str is None:raise ValueError("end_date must be provided")- end_date = datetime.datetime.strptime(end_date_str, TIMESTAMP_FORMAT).replace(- tzinfo=datetime.timezone.utc- )+ end_date = datetime.strptime(end_date_str, TIMESTAMP_FORMAT).replace(tzinfo=timezone.utc)server = RemoteZulipServer.objects.get(id=server_id)self.add_server_to_legacy_plan(server, renewal_date, end_date)@@ -56,8 +54,8 @@ class Command(BaseCommand):def add_server_to_legacy_plan(self,server: RemoteZulipServer,- renewal_date: datetime.datetime,- end_date: datetime.datetime,+ renewal_date: datetime,+ end_date: datetime,) -> None:billing_schedule = RemoteServerBillingSession(server)billing_schedule.add_server_to_legacy_plan(renewal_date, end_date)diff --git a/zilencer/management/commands/populate_billing_realms.py b/zilencer/management/commands/populate_billing_realms.pyindex b99e79e7530..6cc33f8668e 100644--- a/zilencer/management/commands/populate_billing_realms.py+++ b/zilencer/management/commands/populate_billing_realms.py@@ -1,7 +1,7 @@import contextlib-import datetimeimport uuidfrom dataclasses import dataclass+from datetime import datetime, timezonefrom typing import Any, Dict, Optionalimport stripe@@ -304,11 +304,11 @@ def populate_remote_server(customer_profile: CustomerProfile) -> Dict[str, str]:if customer_profile.tier == CustomerPlan.TIER_SELF_HOSTED_LEGACY:# Create customer plan for these servers for temporary period.billing_session = RemoteServerBillingSession(remote_server)- renewal_date = datetime.datetime.strptime(- customer_profile.renewal_date, TIMESTAMP_FORMAT- ).replace(tzinfo=datetime.timezone.utc)- end_date = datetime.datetime.strptime(customer_profile.end_date, TIMESTAMP_FORMAT).replace(- tzinfo=datetime.timezone.utc+ renewal_date = datetime.strptime(customer_profile.renewal_date, TIMESTAMP_FORMAT).replace(+ tzinfo=timezone.utc+ )+ end_date = datetime.strptime(customer_profile.end_date, TIMESTAMP_FORMAT).replace(+ tzinfo=timezone.utc)billing_session.add_server_to_legacy_plan(renewal_date, end_date)elif customer_profile.tier == CustomerPlan.TIER_SELF_HOSTED_BUSINESS:diff --git a/zilencer/views.py b/zilencer/views.pyindex 2bef6f10c3e..2f74f6ebf46 100644--- a/zilencer/views.py+++ b/zilencer/views.py@@ -1,6 +1,6 @@-import datetimeimport loggingfrom collections import Counter+from datetime import datetime, timezonefrom typing import Any, Dict, List, Optional, Type, TypeVar, Unionfrom uuid import UUID@@ -720,7 +720,7 @@ def remote_server_post_analytics(realm_id=row.realm,remote_id=row.id,server=server,- end_time=datetime.datetime.fromtimestamp(row.end_time, tz=datetime.timezone.utc),+ end_time=datetime.fromtimestamp(row.end_time, tz=timezone.utc),subgroup=row.subgroup,value=row.value,)@@ -733,7 +733,7 @@ def remote_server_post_analytics(property=row.property,remote_id=row.id,server=server,- end_time=datetime.datetime.fromtimestamp(row.end_time, tz=datetime.timezone.utc),+ end_time=datetime.fromtimestamp(row.end_time, tz=timezone.utc),subgroup=row.subgroup,value=row.value,)@@ -758,9 +758,7 @@ def remote_server_post_analytics(realm_id=row.realm,remote_id=row.id,server=server,- event_time=datetime.datetime.fromtimestamp(- row.event_time, tz=datetime.timezone.utc- ),+ event_time=datetime.fromtimestamp(row.event_time, tz=timezone.utc),backfilled=row.backfilled,extra_data=extra_data,event_type=row.event_type,