Replace timezone.now with timezone_now.

This commit is contained in:
hackerkid 2017-04-15 07:33:56 +05:30 committed by Tim Abbott
parent 55c3d12078
commit b2504084ab
37 changed files with 147 additions and 146 deletions

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from __future__ import print_function
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from typing import Any, Dict, List
from zerver.models import UserPresence, UserActivity
@ -19,7 +19,7 @@ class Command(BaseCommand):
def handle(self, *args, **options):
# type: (*Any, **Any) -> None
# Get list of all active users in the last 1 week
cutoff = timezone.now() - timedelta(minutes=30, hours=168)
cutoff = timezone_now() - timedelta(minutes=30, hours=168)
users = UserPresence.objects.select_related().filter(timestamp__gt=cutoff)
@ -36,7 +36,7 @@ class Command(BaseCommand):
for bucket in hour_buckets:
if bucket not in user_info[last_presence.user_profile.realm.string_id]:
user_info[last_presence.user_profile.realm.string_id][bucket] = []
if timezone.now() - known_active < timedelta(hours=bucket):
if timezone_now() - known_active < timedelta(hours=bucket):
user_info[last_presence.user_profile.realm.string_id][bucket].append(last_presence.user_profile.email)
for realm, buckets in user_info.items():
@ -52,7 +52,7 @@ class Command(BaseCommand):
for bucket in hour_buckets:
if bucket not in user_info[activity.user_profile.realm.string_id]:
user_info[activity.user_profile.realm.string_id][bucket] = []
if timezone.now() - activity.last_visit < timedelta(hours=bucket):
if timezone_now() - activity.last_visit < timedelta(hours=bucket):
user_info[activity.user_profile.realm.string_id][bucket].append(activity.user_profile.email)
for realm, buckets in user_info.items():
print("Realm %s" % (realm,))

View File

@ -8,7 +8,7 @@ from optparse import make_option
from typing import Any
from django.core.management.base import BaseCommand, CommandParser
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.lib.statistics import activity_averages_during_day
class Command(BaseCommand):
@ -22,7 +22,7 @@ class Command(BaseCommand):
def handle(self, *args, **options):
# type: (*Any, **Any) -> None
if options["date"] is None:
date = timezone.now() - datetime.timedelta(days=1)
date = timezone_now() - datetime.timedelta(days=1)
else:
date = datetime.datetime.strptime(options["date"], "%Y-%m-%d").replace(tzinfo=pytz.utc)
print("Activity data for", date)

View File

@ -6,7 +6,7 @@ from typing import Any
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from django.db.models import Count, QuerySet
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import UserActivity, UserProfile, Realm, \
get_realm, get_user_profile_by_email
@ -39,7 +39,7 @@ Usage examples:
#
# Importantly, this does NOT tell you anything about the relative
# volumes of requests from clients.
threshold = timezone.now() - datetime.timedelta(days=7)
threshold = timezone_now() - datetime.timedelta(days=7)
client_counts = user_activity_objects.filter(
last_visit__gt=threshold).values("client__name").annotate(
count=Count('client__name'))

View File

@ -3,7 +3,7 @@ from __future__ import absolute_import, print_function
from argparse import ArgumentParser
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from analytics.lib.counts import COUNT_STATS, CountStat, do_drop_all_analytics_tables
from analytics.lib.fixtures import generate_time_series_data
@ -53,8 +53,8 @@ class Command(BaseCommand):
# I believe this also deletes any objects with this realm as a foreign key
Realm.objects.filter(string_id='analytics').delete()
installation_time = timezone.now() - timedelta(days=self.DAYS_OF_DATA)
last_end_time = floor_to_day(timezone.now())
installation_time = timezone_now() - timedelta(days=self.DAYS_OF_DATA)
last_end_time = floor_to_day(timezone_now())
realm = Realm.objects.create(
string_id='analytics', name='Analytics', date_created=installation_time)
shylock = self.create_user('shylock@analytics.ds', 'Shylock', True, installation_time, realm)

View File

@ -10,7 +10,7 @@ import pytz
from django.core.management.base import BaseCommand
from django.db.models import Count
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import UserProfile, Realm, Stream, Message, Recipient, UserActivity, \
Subscription, UserMessage, get_realm
@ -31,7 +31,7 @@ class Command(BaseCommand):
def active_users(self, realm):
# type: (Realm) -> List[UserProfile]
# Has been active (on the website, for now) in the last 7 days.
activity_cutoff = timezone.now() - datetime.timedelta(days=7)
activity_cutoff = timezone_now() - datetime.timedelta(days=7)
return [activity.user_profile for activity in (
UserActivity.objects.filter(user_profile__realm=realm,
user_profile__is_active=True,
@ -41,17 +41,17 @@ class Command(BaseCommand):
def messages_sent_by(self, user, days_ago):
# type: (UserProfile, int) -> int
sent_time_cutoff = timezone.now() - datetime.timedelta(days=days_ago)
sent_time_cutoff = timezone_now() - datetime.timedelta(days=days_ago)
return human_messages.filter(sender=user, pub_date__gt=sent_time_cutoff).count()
def total_messages(self, realm, days_ago):
# type: (Realm, int) -> int
sent_time_cutoff = timezone.now() - datetime.timedelta(days=days_ago)
sent_time_cutoff = timezone_now() - datetime.timedelta(days=days_ago)
return Message.objects.filter(sender__realm=realm, pub_date__gt=sent_time_cutoff).count()
def human_messages(self, realm, days_ago):
# type: (Realm, int) -> int
sent_time_cutoff = timezone.now() - datetime.timedelta(days=days_ago)
sent_time_cutoff = timezone_now() - datetime.timedelta(days=days_ago)
return human_messages.filter(sender__realm=realm, pub_date__gt=sent_time_cutoff).count()
def api_messages(self, realm, days_ago):
@ -60,19 +60,19 @@ class Command(BaseCommand):
def stream_messages(self, realm, days_ago):
# type: (Realm, int) -> int
sent_time_cutoff = timezone.now() - datetime.timedelta(days=days_ago)
sent_time_cutoff = timezone_now() - datetime.timedelta(days=days_ago)
return human_messages.filter(sender__realm=realm, pub_date__gt=sent_time_cutoff,
recipient__type=Recipient.STREAM).count()
def private_messages(self, realm, days_ago):
# type: (Realm, int) -> int
sent_time_cutoff = timezone.now() - datetime.timedelta(days=days_ago)
sent_time_cutoff = timezone_now() - datetime.timedelta(days=days_ago)
return human_messages.filter(sender__realm=realm, pub_date__gt=sent_time_cutoff).exclude(
recipient__type=Recipient.STREAM).exclude(recipient__type=Recipient.HUDDLE).count()
def group_private_messages(self, realm, days_ago):
# type: (Realm, int) -> int
sent_time_cutoff = timezone.now() - datetime.timedelta(days=days_ago)
sent_time_cutoff = timezone_now() - datetime.timedelta(days=days_ago)
return human_messages.filter(sender__realm=realm, pub_date__gt=sent_time_cutoff).exclude(
recipient__type=Recipient.STREAM).exclude(recipient__type=Recipient.PERSONAL).count()

View File

@ -9,7 +9,7 @@ from argparse import ArgumentParser
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.utils.timezone import utc as timezone_utc
from django.utils.dateparse import parse_datetime
from django.conf import settings
@ -30,7 +30,7 @@ class Command(BaseCommand):
parser.add_argument('--time', '-t',
type=str,
help='Update stat tables from current state to --time. Defaults to the current time.',
default=timezone.now().isoformat())
default=timezone_now().isoformat())
parser.add_argument('--utc',
type=bool,
help="Interpret --time in UTC.",

View File

@ -7,7 +7,7 @@ import pytz
from typing import Any
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import UserProfile, Realm, Stream, Message, get_realm
from six.moves import range
@ -22,8 +22,8 @@ class Command(BaseCommand):
def messages_sent_by(self, user, week):
# type: (UserProfile, int) -> int
start = timezone.now() - datetime.timedelta(days=(week + 1)*7)
end = timezone.now() - datetime.timedelta(days=week*7)
start = timezone_now() - datetime.timedelta(days=(week + 1)*7)
end = timezone_now() - datetime.timedelta(days=week*7)
return Message.objects.filter(sender=user, pub_date__gt=start, pub_date__lte=end).count()
def handle(self, *args, **options):

View File

@ -4,7 +4,7 @@ from django.apps import apps
from django.db import models
from django.db.models import Sum
from django.test import TestCase
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.utils.timezone import utc as timezone_utc
from analytics.lib.counts import CountStat, COUNT_STATS, process_count_stat, \
@ -918,7 +918,7 @@ class TestActiveUsersAudit(AnalyticsTestCase):
do_deactivate_user(user2)
do_activate_user(user3)
do_reactivate_user(user4)
end_time = floor_to_day(timezone.now()) + self.DAY
end_time = floor_to_day(timezone_now()) + self.DAY
do_fill_count_stat_at_hour(self.stat, end_time)
for user in [user1, user3, user4]:
self.assertTrue(UserCount.objects.filter(
@ -1015,7 +1015,7 @@ class TestRealmActiveHumans(AnalyticsTestCase):
user1 = do_create_user('email1', 'password', self.default_realm, 'full_name', 'short_name')
user2 = do_create_user('email2', 'password', self.default_realm, 'full_name', 'short_name')
do_create_user('email3', 'password', self.default_realm, 'full_name', 'short_name')
time_zero = floor_to_day(timezone.now()) + self.DAY
time_zero = floor_to_day(timezone_now()) + self.DAY
update_user_activity_interval(user1, time_zero)
update_user_activity_interval(user2, time_zero)
do_deactivate_user(user2)

View File

@ -7,7 +7,7 @@ from django.db.models import Sum
from django.db.models.query import QuerySet
from django.http import HttpResponseNotFound, HttpRequest, HttpResponse
from django.template import RequestContext, loader
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext as _
from django.shortcuts import render
from jinja2 import Markup as mark_safe
@ -993,7 +993,7 @@ def realm_user_summary_table(all_records, admin_emails):
def is_recent(val):
# type: (Optional[datetime]) -> bool
age = timezone.now() - val
age = timezone_now() - val
return age.total_seconds() < 5 * 60
rows = []

View File

@ -14,7 +14,7 @@ from django.template import loader, Context
from django.contrib.sites.models import Site
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from confirmation.util import get_status_field
from zerver.lib.utils import generate_random_token
@ -27,7 +27,7 @@ def check_key_is_valid(creation_key):
# type: (Text) -> bool
if not RealmCreationKey.objects.filter(creation_key=creation_key).exists():
return False
days_sofar = (timezone.now() - RealmCreationKey.objects.get(creation_key=creation_key).date_created).days
days_sofar = (timezone_now() - RealmCreationKey.objects.get(creation_key=creation_key).date_created).days
# Realm creation link expires after settings.REALM_CREATION_LINK_VALIDITY_DAYS
if days_sofar <= settings.REALM_CREATION_LINK_VALIDITY_DAYS:
return True
@ -49,7 +49,7 @@ def generate_activation_url(key, host=None):
def generate_realm_creation_url():
# type: () -> Text
key = generate_key()
RealmCreationKey.objects.create(creation_key=key, date_created=timezone.now())
RealmCreationKey.objects.create(creation_key=key, date_created=timezone_now())
return u'%s%s%s' % (settings.EXTERNAL_URI_SCHEME,
settings.EXTERNAL_HOST,
reverse('zerver.views.create_realm',
@ -66,7 +66,7 @@ class ConfirmationManager(models.Manager):
return False
max_days = self.get_link_validity_in_days()
time_elapsed = timezone.now() - confirmation.date_sent
time_elapsed = timezone_now() - confirmation.date_sent
if time_elapsed.total_seconds() > max_days * 24 * 3600:
return False
@ -80,7 +80,7 @@ class ConfirmationManager(models.Manager):
def get_link_for_object(self, obj, host=None):
# type: (Union[ContentType, int], Optional[str]) -> Text
key = generate_key()
self.create(content_object=obj, date_sent=timezone.now(), confirmation_key=key)
self.create(content_object=obj, date_sent=timezone_now(), confirmation_key=key)
return self.get_activation_url(key, host=host)
def get_activation_url(self, confirmation_key, host=None):
@ -137,7 +137,7 @@ class ConfirmationManager(models.Manager):
if html_template:
html_content = html_template.render(context)
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [email_address], html_message=html_content)
return self.create(content_object=obj, date_sent=timezone.now(), confirmation_key=confirmation_key)
return self.create(content_object=obj, date_sent=timezone_now(), confirmation_key=confirmation_key)
class EmailChangeConfirmationManager(ConfirmationManager):
def get_activation_url(self, key, host=None):
@ -179,4 +179,4 @@ class EmailChangeConfirmation(Confirmation):
class RealmCreationKey(models.Model):
creation_key = models.CharField('activation key', max_length=40)
date_created = models.DateTimeField('created', default=timezone.now)
date_created = models.DateTimeField('created', default=timezone_now)

View File

@ -18,7 +18,7 @@ sys.path.append('/home/zulip/deployments/current')
import scripts.lib.setup_path_on_import
import django
from django.utils import timezone
from django.utils.timezone import now as timezone_now
os.environ['DJANGO_SETTINGS_MODULE'] = "zproject.settings"
sys.path.append('/home/zulip/deployments/current')
@ -51,7 +51,7 @@ def report(state, short_msg, too_old=None):
exit(states[state])
now = timezone.now()
now = timezone_now()
all_users = UserActivity.objects.filter(query__in=["get_events_backend", "/api/v1/events"],
client__name="zephyr_mirror")

View File

@ -10,7 +10,7 @@ from zerver.models import UserProfile, get_client, get_user_profile_by_email
from zerver.lib.response import json_error, json_unauthorized, json_success
from django.shortcuts import resolve_url
from django.utils.decorators import available_attrs
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.conf import settings
from zerver.lib.queue import queue_json_publish
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
@ -84,7 +84,7 @@ def update_user_activity(request, user_profile):
event = {'query': query,
'user_profile_id': user_profile.id,
'time': datetime_to_timestamp(timezone.now()),
'time': datetime_to_timestamp(timezone_now()),
'client': request.client.name}
queue_json_publish("user_activity", event, lambda event: None)

View File

@ -49,7 +49,7 @@ from django.db.models import F, Q
from django.db.models.query import QuerySet
from django.core.exceptions import ValidationError
from django.core.mail import EmailMessage
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from confirmation.models import Confirmation, EmailChangeConfirmation
import six
@ -118,7 +118,7 @@ def log_event(event):
template = os.path.join(settings.EVENT_LOG_DIR,
'%s.' + platform.node() +
timezone.now().strftime('.%Y-%m-%d'))
timezone_now().strftime('.%Y-%m-%d'))
with lockfile(template % ('lock',)):
with open(template % ('events',), 'a') as log:
@ -267,7 +267,7 @@ def add_new_user_history(user_profile, streams):
"""Give you the last 100 messages on your public streams, so you have
something to look at in your home view once you finish the
tutorial."""
one_week_ago = timezone.now() - datetime.timedelta(weeks=1)
one_week_ago = timezone_now() - datetime.timedelta(weeks=1)
recipients = Recipient.objects.filter(type=Recipient.STREAM,
type_id__in=[stream.id for stream in streams
if not stream.invite_only])
@ -349,7 +349,7 @@ def process_new_human_user(user_profile, prereg_user=None, newsletter_data=None)
'NAME': user_profile.full_name,
'REALM_ID': user_profile.realm_id,
'OPTIN_IP': newsletter_data["IP"],
'OPTIN_TIME': datetime.datetime.isoformat(timezone.now().replace(microsecond=0)),
'OPTIN_TIME': datetime.datetime.isoformat(timezone_now().replace(microsecond=0)),
},
},
lambda event: None)
@ -517,7 +517,7 @@ def do_deactivate_user(user_profile, _cascade=True):
delete_user_sessions(user_profile)
event_time = timezone.now()
event_time = timezone_now()
RealmAuditLog.objects.create(realm=user_profile.realm, modified_user=user_profile,
event_type='user_deactivated', event_time=event_time)
do_increment_logging_stat(user_profile.realm, COUNT_STATS['active_users_log:is_bot:day'],
@ -597,7 +597,7 @@ def do_change_user_email(user_profile, new_email):
new_email=new_email)
send_event(dict(type='realm_user', op='update', person=payload),
active_user_ids(user_profile.realm))
event_time = timezone.now()
event_time = timezone_now()
RealmAuditLog.objects.create(realm=user_profile.realm, acting_user=user_profile,
modified_user=user_profile, event_type='user_email_changed',
event_time=event_time)
@ -1119,7 +1119,7 @@ def send_pm_if_empty_stream(sender, stream, stream_name, realm):
# 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)
if last_reminder and timezone.now() - last_reminder <= waitperiod:
if last_reminder and timezone_now() - last_reminder <= waitperiod:
return
if stream is None:
@ -1136,7 +1136,7 @@ def send_pm_if_empty_stream(sender, stream, stream_name, realm):
sender.bot_owner.email, "", content)
do_send_messages([message])
sender.last_reminder = timezone.now()
sender.last_reminder = timezone_now()
sender.save(update_fields=['last_reminder'])
# check_message:
@ -1223,7 +1223,7 @@ def check_message(sender, client, message_type_name, message_to,
# Forged messages come with a timestamp
message.pub_date = timestamp_to_datetime(forged_timestamp)
else:
message.pub_date = timezone.now()
message.pub_date = timezone_now()
message.sending_client = client
# We render messages later in the process.
@ -1707,7 +1707,7 @@ def do_activate_user(user_profile):
user_profile.is_active = True
user_profile.is_mirror_dummy = False
user_profile.set_unusable_password()
user_profile.date_joined = timezone.now()
user_profile.date_joined = timezone_now()
user_profile.tos_version = settings.TOS_VERSION
user_profile.save(update_fields=["is_active", "date_joined", "password",
"is_mirror_dummy", "tos_version"])
@ -1727,7 +1727,7 @@ def do_reactivate_user(user_profile):
user_profile.is_active = True
user_profile.save(update_fields=["is_active"])
event_time = timezone.now()
event_time = timezone_now()
RealmAuditLog.objects.create(realm=user_profile.realm, modified_user=user_profile,
event_type='user_reactivated', event_time=event_time)
do_increment_logging_stat(user_profile.realm, COUNT_STATS['active_users_log:is_bot:day'],
@ -1748,7 +1748,7 @@ def do_change_password(user_profile, password, commit=True,
user_profile.set_password(password)
if commit:
user_profile.save(update_fields=["password"])
event_time = timezone.now()
event_time = timezone_now()
RealmAuditLog.objects.create(realm=user_profile.realm, acting_user=user_profile,
modified_user=user_profile, event_type='user_change_password',
event_time=event_time)
@ -1775,7 +1775,7 @@ def do_change_bot_owner(user_profile, bot_owner, acting_user):
# type: (UserProfile, UserProfile, UserProfile) -> None
user_profile.bot_owner = bot_owner
user_profile.save()
event_time = timezone.now()
event_time = timezone_now()
RealmAuditLog.objects.create(realm=user_profile.realm, acting_user=acting_user,
modified_user=user_profile, event_type='bot_owner_changed',
event_time=event_time)
@ -1819,7 +1819,7 @@ def do_change_avatar_fields(user_profile, avatar_source):
user_profile.avatar_source = avatar_source
user_profile.avatar_version += 1
user_profile.save(update_fields=["avatar_source", "avatar_version"])
event_time = timezone.now()
event_time = timezone_now()
RealmAuditLog.objects.create(realm=user_profile.realm, modified_user=user_profile,
event_type='user_change_avatar_source',
extra_data={'avatar_source': avatar_source},
@ -2684,10 +2684,10 @@ def do_update_message(user_profile, message, subject, propagate_mode, content, r
# We only change messages up to 2 days in the past, to avoid hammering our
# DB by changing an unbounded amount of messages
if propagate_mode == 'change_all':
before_bound = timezone.now() - datetime.timedelta(days=2)
before_bound = timezone_now() - datetime.timedelta(days=2)
propagate_query = (propagate_query & ~Q(id = message.id) &
Q(pub_date__range=(before_bound, timezone.now())))
Q(pub_date__range=(before_bound, timezone_now())))
if propagate_mode == 'change_later':
propagate_query = propagate_query & Q(id__gt = message.id)
@ -2704,7 +2704,7 @@ def do_update_message(user_profile, message, subject, propagate_mode, content, r
changed_messages += messages_list
message.last_edit_time = timezone.now()
message.last_edit_time = timezone_now()
event['edit_timestamp'] = datetime_to_timestamp(message.last_edit_time)
edit_history_event['timestamp'] = event['edit_timestamp']
if message.edit_history is not None:

View File

@ -1,7 +1,7 @@
from __future__ import absolute_import
from django.contrib.auth.models import UserManager
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import UserProfile, Recipient, Subscription, Realm, Stream
import base64
import ujson
@ -29,7 +29,7 @@ def create_user_profile(realm, email, password, active, bot_type, full_name,
tutorial_status=UserProfile.TUTORIAL_WAITING,
enter_sends=False):
# type: (Realm, Text, Optional[Text], bool, Optional[int], Text, Text, Optional[UserProfile], bool, Optional[Text], Optional[Text], bool) -> UserProfile
now = timezone.now()
now = timezone_now()
email = UserManager.normalize_email(email)
user_profile = UserProfile(email=email, is_staff=False, is_active=active,

View File

@ -1,6 +1,6 @@
from __future__ import absolute_import
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.utils.timezone import utc as timezone_utc
import hashlib
@ -42,10 +42,10 @@ class _RateLimitFilter(object):
if not duplicate:
cache.set(key, 1, rate)
else:
min_date = timezone.now() - timedelta(seconds=rate)
min_date = timezone_now() - timedelta(seconds=rate)
duplicate = (self.last_error >= min_date)
if not duplicate:
self.last_error = timezone.now()
self.last_error = timezone_now()
return not duplicate

View File

@ -7,7 +7,7 @@ from confirmation.models import Confirmation
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.decorator import statsd_increment, uses_mandrill
from zerver.lib.queue import queue_json_publish
from zerver.models import (
@ -308,7 +308,7 @@ def do_send_missedmessage_events_reply_in_zulip(user_profile, missed_messages, m
}
queue_json_publish("missedmessage_email_senders", email_content, send_missedmessage_email)
user_profile.last_reminder = timezone.now()
user_profile.last_reminder = timezone_now()
user_profile.save(update_fields=['last_reminder'])
@ -438,7 +438,7 @@ def send_future_email(recipients, email_html, email_text, subject,
'sender_name': sender['name']}
ScheduledJob.objects.create(type=ScheduledJob.EMAIL, filter_string=recipient.get('email'),
data=ujson.dumps(email_fields),
scheduled_timestamp=timezone.now() + delay)
scheduled_timestamp=timezone_now() + delay)
return
# Mandrill implementation
@ -461,7 +461,7 @@ def send_future_email(recipients, email_html, email_text, subject,
if delay < datetime.timedelta(minutes=1):
results = mail_client.messages.send(message=message, ip_pool="Main Pool", **{"async": False})
else:
send_time = (timezone.now() + delay).__format__("%Y-%m-%d %H:%M:%S")
send_time = (timezone_now() + delay).__format__("%Y-%m-%d %H:%M:%S")
results = mail_client.messages.send(message=message, ip_pool="Main Pool",
send_at=send_time, **{"async": False})
problems = [result for result in results if (result['status'] in ('rejected', 'invalid'))]

View File

@ -18,7 +18,7 @@ from apns import APNs, Frame, Payload, SENT_BUFFER_QTY
from gcm import GCM
from django.conf import settings
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext as _
import base64
@ -354,7 +354,7 @@ def add_push_device_token(user_profile, token_str, kind, ios_app_id=None):
kind=kind,
ios_app_id=ios_app_id))
if not created:
token.last_updated = timezone.now()
token.last_updated = timezone_now()
token.save(update_fields=['last_updated'])
def remove_push_device_token(user_profile, token_str, kind):

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import
from __future__ import print_function
from datetime import timedelta
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import Realm, Message
from typing import Any, Dict, Optional, Generator
@ -10,7 +10,7 @@ from typing import Any, Dict, Optional, Generator
def get_realm_expired_messages(realm):
# type: (Any) -> Optional[Dict[str, Any]]
expired_date = timezone.now() - timedelta(days=realm.message_retention_days)
expired_date = timezone_now() - timedelta(days=realm.message_retention_days)
expired_messages = Message.objects.order_by('id').filter(sender__realm=realm,
pub_date__lt=expired_date)
if not expired_messages.exists():

View File

@ -5,7 +5,7 @@ import logging
from django.conf import settings
from django.contrib.auth import SESSION_KEY, get_user_model
from django.contrib.sessions.models import Session
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from importlib import import_module
from typing import List, Mapping, Optional, Text
@ -44,7 +44,7 @@ def delete_realm_user_sessions(realm):
# type: (Realm) -> None
realm_user_ids = [user_profile.id for user_profile in
UserProfile.objects.filter(realm=realm)]
for session in Session.objects.filter(expire_date__gte=timezone.now()):
for session in Session.objects.filter(expire_date__gte=timezone_now()):
if get_session_user(session) in realm_user_ids:
delete_session(session)

View File

@ -2,7 +2,7 @@ from __future__ import absolute_import, print_function
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import UserProfile
import argparse
@ -28,7 +28,7 @@ class Command(BaseCommand):
parser.add_argument('--optin-time',
dest='optin_time',
type=str,
default=datetime.isoformat(timezone.now().replace(microsecond=0)),
default=datetime.isoformat(timezone_now().replace(microsecond=0)),
help='Opt-in time of the users.')
def handle(self, *args, **options):

View File

@ -13,7 +13,7 @@ from __future__ import absolute_import
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.mail import get_connection, send_mail
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.utils.html import format_html
from zerver.models import ScheduledJob
@ -87,7 +87,7 @@ Usage: ./manage.py deliver_email
with lockfile("/tmp/zulip_email_deliver.lockfile"):
while True:
email_jobs_to_deliver = ScheduledJob.objects.filter(type=ScheduledJob.EMAIL,
scheduled_timestamp__lte=timezone.now())
scheduled_timestamp__lte=timezone_now())
if email_jobs_to_deliver:
for job in email_jobs_to_deliver:
if not send_email_job(job):

View File

@ -6,7 +6,7 @@ from typing import Any, List
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.lib.queue import queue_json_publish
from zerver.models import UserActivity, UserProfile, Realm
@ -43,7 +43,7 @@ def inactive_since(user_profile, cutoff):
def last_business_day():
# type: () -> datetime.datetime
one_day = datetime.timedelta(hours=23)
previous_day = timezone.now() - one_day
previous_day = timezone_now() - one_day
while previous_day.weekday() not in VALID_DIGEST_DAYS:
previous_day -= one_day
return previous_day
@ -74,7 +74,7 @@ in a while.
# To be really conservative while we don't have user timezones or
# special-casing for companies with non-standard workweeks, only
# try to send mail on Tuesdays, Wednesdays, and Thursdays.
if timezone.now().weekday() not in VALID_DIGEST_DAYS:
if timezone_now().weekday() not in VALID_DIGEST_DAYS:
return
for realm in Realm.objects.filter(deactivated=False, show_digest_email=True):

View File

@ -10,7 +10,7 @@ from __future__ import print_function
from typing import Any
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import ScheduledJob
@ -29,4 +29,4 @@ Usage: ./manage.py print_email_delivery_backlog
def handle(self, *args, **options):
# type: (*Any, **Any) -> None
print(len(ScheduledJob.objects.filter(type=ScheduledJob.EMAIL,
scheduled_timestamp__lte=timezone.now()-timedelta(minutes=1))))
scheduled_timestamp__lte=timezone_now()-timedelta(minutes=1))))

View File

@ -9,11 +9,11 @@ from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils import timezone
from django.utils.timezone import now as timezone_now
def backfill_user_activations_and_deactivations(apps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
migration_time = timezone.now()
migration_time = timezone_now()
RealmAuditLog = apps.get_model('zerver', 'RealmAuditLog')
UserProfile = apps.get_model('zerver', 'UserProfile')

View File

@ -25,7 +25,7 @@ from zerver.lib.utils import make_safe_digest, generate_random_token
from zerver.lib.str_utils import ModelReprMixin
from django.db import transaction
from zerver.lib.camo import get_camo_url
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.contrib.sessions.models import Session
from zerver.lib.timestamp import datetime_to_timestamp
from django.db.models.signals import pre_save, post_save, post_delete
@ -132,7 +132,7 @@ class Realm(ModelReprMixin, models.Model):
COMMUNITY = 2
org_type = models.PositiveSmallIntegerField(default=COMMUNITY) # type: int
date_created = models.DateTimeField(default=timezone.now) # type: datetime.datetime
date_created = models.DateTimeField(default=timezone_now) # type: datetime.datetime
notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True) # type: Optional[Stream]
deactivated = models.BooleanField(default=False) # type: bool
default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: Text
@ -525,7 +525,7 @@ class UserProfile(ModelReprMixin, AbstractBaseUser, PermissionsMixin):
is_bot = models.BooleanField(default=False, db_index=True) # type: bool
bot_type = models.PositiveSmallIntegerField(null=True, db_index=True) # type: Optional[int]
is_api_super_user = models.BooleanField(default=False, db_index=True) # type: bool
date_joined = models.DateTimeField(default=timezone.now) # type: datetime.datetime
date_joined = models.DateTimeField(default=timezone_now) # type: datetime.datetime
is_mirror_dummy = models.BooleanField(default=False) # type: bool
bot_owner = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) # type: Optional[UserProfile]
@ -565,7 +565,7 @@ class UserProfile(ModelReprMixin, AbstractBaseUser, PermissionsMixin):
###
last_reminder = models.DateTimeField(default=timezone.now, null=True) # type: Optional[datetime.datetime]
last_reminder = models.DateTimeField(default=timezone_now, null=True) # type: Optional[datetime.datetime]
rate_limits = models.CharField(default=u"", max_length=100) # type: Text # comma-separated list of range:max pairs
# Default streams
@ -669,7 +669,7 @@ class UserProfile(ModelReprMixin, AbstractBaseUser, PermissionsMixin):
def can_create_streams(self):
# type: () -> bool
diff = (timezone.now() - self.date_joined).days
diff = (timezone_now() - self.date_joined).days
if self.is_realm_admin:
return True
elif self.realm.create_stream_by_admins_only:
@ -771,7 +771,7 @@ class Stream(ModelReprMixin, models.Model):
max_length=32, default=generate_email_token_for_stream) # type: Text
description = models.CharField(max_length=1024, default=u'') # type: Text
date_created = models.DateTimeField(default=timezone.now) # type: datetime.datetime
date_created = models.DateTimeField(default=timezone_now) # type: datetime.datetime
deactivated = models.BooleanField(default=False) # type: bool
def __unicode__(self):
@ -975,7 +975,7 @@ class AbstractMessage(ModelReprMixin, models.Model):
class ArchivedMessage(AbstractMessage):
archive_timestamp = models.DateTimeField(default=timezone.now, db_index=True) # type: datetime.datetime
archive_timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
class Message(AbstractMessage):
@ -1175,7 +1175,7 @@ class AbstractUserMessage(ModelReprMixin, models.Model):
class ArchivedUserMessage(AbstractUserMessage):
message = models.ForeignKey(ArchivedMessage) # type: Message
archive_timestamp = models.DateTimeField(default=timezone.now, db_index=True) # type: datetime.datetime
archive_timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
class UserMessage(AbstractUserMessage):
@ -1207,7 +1207,7 @@ class AbstractAttachment(ModelReprMixin, models.Model):
owner = models.ForeignKey(UserProfile) # type: UserProfile
realm = models.ForeignKey(Realm, blank=True, null=True) # type: Realm
is_realm_public = models.BooleanField(default=False) # type: bool
create_time = models.DateTimeField(default=timezone.now,
create_time = models.DateTimeField(default=timezone_now,
db_index=True) # type: datetime.datetime
size = models.IntegerField(null=True) # type: int
@ -1216,7 +1216,7 @@ class AbstractAttachment(ModelReprMixin, models.Model):
class ArchivedAttachment(AbstractAttachment):
archive_timestamp = models.DateTimeField(default=timezone.now, db_index=True) # type: datetime.datetime
archive_timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
messages = models.ManyToManyField(ArchivedMessage) # type: Manager
@ -1269,7 +1269,7 @@ def validate_attachment_request(user_profile, path_id):
def get_old_unclaimed_attachments(weeks_ago):
# type: (int) -> Sequence[Attachment]
# TODO: Change return type to QuerySet[Attachment]
delta_weeks_ago = timezone.now() - datetime.timedelta(weeks=weeks_ago)
delta_weeks_ago = timezone_now() - datetime.timedelta(weeks=weeks_ago)
old_attachments = Attachment.objects.filter(messages=None, create_time__lt=delta_weeks_ago)
return old_attachments
@ -1462,7 +1462,7 @@ class UserPresence(models.Model):
@staticmethod
def exclude_old_users(query):
# type: (QuerySet) -> QuerySet
two_weeks_ago = timezone.now() - datetime.timedelta(weeks=2)
two_weeks_ago = timezone_now() - datetime.timedelta(weeks=2)
return query.filter(timestamp__gte=two_weeks_ago)
@staticmethod
@ -1598,7 +1598,7 @@ class RealmAuditLog(models.Model):
class UserHotspot(models.Model):
user = models.ForeignKey(UserProfile) # type: UserProfile
hotspot = models.CharField(max_length=30) # type: Text
timestamp = models.DateTimeField(default=timezone.now) # type: datetime.datetime
timestamp = models.DateTimeField(default=timezone_now) # type: datetime.datetime
class Meta(object):
unique_together = ("user", "hotspot")

View File

@ -6,6 +6,7 @@ from django.core.mail import send_mail
from django.conf import settings
from django.template import loader
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from typing import Any, Dict, Optional
from zerver.models import UserProfile
@ -67,7 +68,7 @@ def email_on_new_login(sender, user, request, **kwargs):
if path == "/accounts/register/":
return
login_time = timezone.now().strftime('%A, %B %d, %Y at %I:%M%p ') + \
login_time = timezone_now().strftime('%A, %B %d, %Y at %I:%M%p ') + \
timezone.get_current_timezone_name()
user_agent = request.META.get('HTTP_USER_AGENT', "").lower()
device_browser = get_device_browser(user_agent)

View File

@ -1,5 +1,5 @@
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.lib.actions import do_create_user, do_deactivate_user, \
do_activate_user, do_reactivate_user, do_change_password, \
@ -14,7 +14,7 @@ class TestRealmAuditLog(ZulipTestCase):
def test_user_activation(self):
# type: () -> None
realm = get_realm('zulip')
now = timezone.now()
now = timezone_now()
user = do_create_user('email', 'password', realm, 'full_name', 'short_name')
do_deactivate_user(user)
do_activate_user(user)
@ -30,7 +30,7 @@ class TestRealmAuditLog(ZulipTestCase):
def test_change_password(self):
# type: () -> None
now = timezone.now()
now = timezone_now()
user = get_user_profile_by_email("hamlet@zulip.com")
password = 'test1'
do_change_password(user, password)
@ -40,7 +40,7 @@ class TestRealmAuditLog(ZulipTestCase):
def test_change_email(self):
# type: () -> None
now = timezone.now()
now = timezone_now()
user = get_user_profile_by_email("hamlet@zulip.com")
email = 'test@example.com'
do_change_user_email(user, email)
@ -50,7 +50,7 @@ class TestRealmAuditLog(ZulipTestCase):
def test_change_avatar_source(self):
# type: () -> None
now = timezone.now()
now = timezone_now()
user = get_user_profile_by_email("hamlet@zulip.com")
avatar_source = u'G'
do_change_avatar_fields(user, avatar_source)
@ -60,7 +60,7 @@ class TestRealmAuditLog(ZulipTestCase):
def test_change_bot_owner(self):
# type: () -> None
now = timezone.now()
now = timezone_now()
admin = get_user_profile_by_email('iago@zulip.com')
bot = get_user_profile_by_email("notification-bot@zulip.com")
bot_owner = get_user_profile_by_email("hamlet@zulip.com")

View File

@ -8,7 +8,7 @@ from typing import Any, Callable, Dict, List, Optional, Union, Text
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import (
get_client, get_realm, get_recipient, get_stream, get_user_profile_by_email,
@ -592,7 +592,7 @@ class EventsRegisterTest(ZulipTestCase):
with self.assertRaises(AssertionError):
events = self.do_test(lambda: do_update_user_presence(
self.user_profile, get_client("website"), timezone.now(), UserPresence.ACTIVE))
self.user_profile, get_client("website"), timezone_now(), UserPresence.ACTIVE))
# Marked as nocoverage since unreachable
error = schema_checker('events[0]', events[0]) # nocoverage
self.assert_on_error(error) # nocoverage

View File

@ -4,7 +4,7 @@ from django.db.models import Q
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase, override_settings
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.lib import bugdown
from zerver.decorator import JsonableError
from zerver.lib.test_runner import slow
@ -77,7 +77,7 @@ class TopicHistoryTest(ZulipTestCase):
recipient=recipient,
subject=topic,
content='whatever',
pub_date=timezone.now(),
pub_date=timezone_now(),
sending_client=get_client('whatever'),
)
flags = 0
@ -576,9 +576,9 @@ class MessageDictTest(ZulipTestCase):
recipient=recipient,
subject='whatever',
content='whatever %d' % i,
pub_date=timezone.now(),
pub_date=timezone_now(),
sending_client=sending_client,
last_edit_time=timezone.now(),
last_edit_time=timezone_now(),
edit_history='[]'
)
message.save()
@ -615,9 +615,9 @@ class MessageDictTest(ZulipTestCase):
recipient=recipient,
subject='whatever',
content='hello **world**',
pub_date=timezone.now(),
pub_date=timezone_now(),
sending_client=sending_client,
last_edit_time=timezone.now(),
last_edit_time=timezone_now(),
edit_history='[]'
)
message.save()
@ -646,9 +646,9 @@ class MessageDictTest(ZulipTestCase):
recipient=recipient,
subject='whatever',
content='hello **world**',
pub_date=timezone.now(),
pub_date=timezone_now(),
sending_client=sending_client,
last_edit_time=timezone.now(),
last_edit_time=timezone_now(),
edit_history='[]'
)
message.save()
@ -671,9 +671,9 @@ class MessageDictTest(ZulipTestCase):
recipient=recipient,
subject='whatever',
content='hello **world**',
pub_date=timezone.now(),
pub_date=timezone_now(),
sending_client=sending_client,
last_edit_time=timezone.now(),
last_edit_time=timezone_now(),
edit_history='[]'
)
message.save()
@ -713,9 +713,9 @@ class SewMessageAndReactionTest(ZulipTestCase):
recipient=recipient,
subject='whatever',
content='whatever %d' % i,
pub_date=timezone.now(),
pub_date=timezone_now(),
sending_client=sending_client,
last_edit_time=timezone.now(),
last_edit_time=timezone_now(),
edit_history='[]'
)
message.save()

View File

@ -3,7 +3,7 @@ from __future__ import absolute_import
from __future__ import print_function
from django.http import HttpResponse
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from mock import mock
from typing import Any, Dict
@ -35,7 +35,7 @@ class ActivityTest(ZulipTestCase):
self.login("hamlet@zulip.com")
client, _ = Client.objects.get_or_create(name='website')
query = '/json/users/me/pointer'
last_visit = timezone.now()
last_visit = timezone_now()
count = 150
for user_profile in UserProfile.objects.all():
UserActivity.objects.get_or_create(
@ -81,7 +81,7 @@ class UserPresenceModelTests(ZulipTestCase):
def back_date(num_weeks):
# type: (int) -> None
user_presence = UserPresence.objects.filter(user_profile=user_profile)[0]
user_presence.timestamp = timezone.now() - datetime.timedelta(weeks=num_weeks)
user_presence.timestamp = timezone_now() - datetime.timedelta(weeks=num_weeks)
user_presence.save()
# Simulate the presence being a week old first. Nothing should change.
@ -184,7 +184,7 @@ class UserPresenceTests(ZulipTestCase):
def _simulate_mirror_activity_for_user(self, user_profile):
# type: (UserProfile) -> None
last_visit = timezone.now()
last_visit = timezone_now()
client = make_client('zephyr_mirror')
UserActivity.objects.get_or_create(
@ -300,7 +300,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
def test_aggregated_info(self):
# type: () -> None
email = "othello@zulip.com"
validate_time = timezone.now()
validate_time = timezone_now()
self._send_presence_for_aggregated_tests('othello@zulip.com', 'active', validate_time)
with mock.patch('django.utils.timezone.now',
return_value=validate_time - datetime.timedelta(seconds=1)):
@ -319,7 +319,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
def test_aggregated_presense_active(self):
# type: () -> None
validate_time = timezone.now()
validate_time = timezone_now()
result_dict = self._send_presence_for_aggregated_tests('othello@zulip.com', 'active',
validate_time)
self.assertDictEqual(
@ -332,7 +332,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
def test_aggregated_presense_idle(self):
# type: () -> None
validate_time = timezone.now()
validate_time = timezone_now()
result_dict = self._send_presence_for_aggregated_tests('othello@zulip.com', 'idle',
validate_time)
self.assertDictEqual(
@ -347,7 +347,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
# type: () -> None
email = "othello@zulip.com"
self.login(email)
validate_time = timezone.now()
validate_time = timezone_now()
with mock.patch('django.utils.timezone.now',
return_value=validate_time - datetime.timedelta(seconds=3)):
self.client_post("/api/v1/users/me/presence", {'status': 'active'},
@ -366,7 +366,7 @@ class UserPresenceAggregationTests(ZulipTestCase):
# type: () -> None
email = "othello@zulip.com"
self.login(email)
validate_time = timezone.now()
validate_time = timezone_now()
with self.settings(OFFLINE_THRESHOLD_SECS=1):
result_dict = self._send_presence_for_aggregated_tests(email, 'idle', validate_time)
self.assertDictEqual(

View File

@ -3,7 +3,7 @@ from __future__ import absolute_import
import types
from datetime import datetime, timedelta
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.lib.test_classes import ZulipTestCase
from zerver.models import Message, Realm, Recipient, UserProfile
from zerver.lib.retention import get_expired_messages
@ -64,12 +64,12 @@ class TestRetentionLib(ZulipTestCase):
# type: () -> None
# Check result realm messages order and result content
# when all realm has expired messages.
expired_mit_messages = self._make_mit_messages(3, timezone.now() - timedelta(days=101))
self._make_mit_messages(4, timezone.now() - timedelta(days=50))
expired_mit_messages = self._make_mit_messages(3, timezone_now() - timedelta(days=101))
self._make_mit_messages(4, timezone_now() - timedelta(days=50))
zulip_messages_ids = Message.objects.order_by('id').filter(
sender__realm=self.zulip_realm).values_list('id', flat=True)[3:10]
expired_zulip_messages = self._change_messages_pub_date(zulip_messages_ids,
timezone.now() - timedelta(days=31))
timezone_now() - timedelta(days=31))
# Iterate by result
expired_messages_result = [messages_list for messages_list in get_expired_messages()]
self.assertEqual(len(expired_messages_result), 2)
@ -93,8 +93,8 @@ class TestRetentionLib(ZulipTestCase):
# type: () -> None
# Check realm with expired messages and messages
# with one day to expiration data.
expired_mit_messages = self._make_mit_messages(5, timezone.now() - timedelta(days=101))
actual_mit_messages = self._make_mit_messages(3, timezone.now() - timedelta(days=99))
expired_mit_messages = self._make_mit_messages(5, timezone_now() - timedelta(days=101))
actual_mit_messages = self._make_mit_messages(3, timezone_now() - timedelta(days=99))
expired_messages_result = list(get_expired_messages())
expired_mit_messages_ids = [message.id for message in expired_mit_messages]
expired_mit_messages_result_ids = [message.id for message in

View File

@ -6,7 +6,7 @@ from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.http import HttpResponse
from django.test import TestCase
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from mock import patch, MagicMock
from zerver.lib.test_helpers import MockLDAP
@ -664,7 +664,7 @@ so we didn't send them an invitation. We did send invitations to everyone else!"
sender={'email': settings.ZULIP_ADMINISTRATOR, 'name': 'Zulip'})
email_jobs_to_deliver = ScheduledJob.objects.filter(
type=ScheduledJob.EMAIL,
scheduled_timestamp__lte=timezone.now())
scheduled_timestamp__lte=timezone_now())
self.assertEqual(len(email_jobs_to_deliver), 1)
email_count = len(outbox)
for job in email_jobs_to_deliver:

View File

@ -42,7 +42,7 @@ import datetime
import requests
import base64
from datetime import timedelta
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from moto import mock_s3
@ -263,7 +263,7 @@ class FileUploadTest(UploadSerializeMixin, ZulipTestCase):
uri = json["uri"]
d2_path_id = re.sub('/user_uploads/', '', uri)
two_week_ago = timezone.now() - datetime.timedelta(weeks=2)
two_week_ago = timezone_now() - datetime.timedelta(weeks=2)
d1_attachment = Attachment.objects.get(path_id = d1_path_id)
d1_attachment.create_time = two_week_ago
d1_attachment.save()

View File

@ -6,7 +6,7 @@ from typing import cast, AbstractSet, Any, Callable, Dict, List, \
from django.utils.translation import ugettext as _
from django.conf import settings
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from collections import deque
import datetime
import os
@ -678,7 +678,7 @@ def receiver_is_idle(user_profile_id, realm_presences):
else:
active_datetime = timestamp_to_datetime(latest_active_timestamp)
# 140 seconds is consistent with presence.js:OFFLINE_THRESHOLD_SECS
idle = timezone.now() - active_datetime > datetime.timedelta(seconds=140)
idle = timezone_now() - active_datetime > datetime.timedelta(seconds=140)
return off_zulip or idle

View File

@ -3,7 +3,7 @@ from __future__ import absolute_import
from typing import Any, Dict, Mapping, Optional, Text, Union
from django.conf import settings
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.contrib.sessions.models import Session as djSession
try:
from django.middleware.csrf import _compare_salted_tokens
@ -39,7 +39,7 @@ def get_user_profile(session_id):
return None
try:
djsession = djSession.objects.get(expire_date__gt=timezone.now(),
djsession = djSession.objects.get(expire_date__gt=timezone_now(),
session_key=session_id)
except djSession.DoesNotExist:
return None

View File

@ -1,7 +1,7 @@
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from django.conf import settings
from django.core import validators
from django.core.exceptions import ValidationError
@ -971,7 +971,7 @@ def update_message_backend(request, user_profile,
edit_limit_buffer = 20
if content is not None and user_profile.realm.message_content_edit_limit_seconds > 0:
deadline_seconds = user_profile.realm.message_content_edit_limit_seconds + edit_limit_buffer
if (timezone.now() - message.pub_date) > datetime.timedelta(seconds=deadline_seconds):
if (timezone_now() - message.pub_date) > datetime.timedelta(seconds=deadline_seconds):
raise JsonableError(_("The time limit for editing this message has past"))
if subject is None and content is None:

View File

@ -3,7 +3,7 @@ from __future__ import division
from __future__ import print_function
from django.core.management.base import BaseCommand, CommandParser
from django.utils import timezone
from django.utils.timezone import now as timezone_now
from zerver.models import Message, UserProfile, Stream, Recipient, UserPresence, \
Subscription, get_huddle, Realm, UserMessage, RealmDomain, \
@ -193,7 +193,7 @@ class Command(BaseCommand):
# Populate users with some bar data
for user in user_profiles:
status = UserPresence.ACTIVE # type: int
date = timezone.now()
date = timezone_now()
client = get_client("website")
if user.full_name[0] <= 'H':
client = get_client("ZulipAndroid")
@ -405,7 +405,7 @@ def send_messages(data):
message.subject = stream.name + Text(random.randint(1, 3))
saved_data['subject'] = message.subject
message.pub_date = timezone.now()
message.pub_date = timezone_now()
do_send_messages([{'message': message}])
recipients[num_messages] = (message_type, message.recipient.id, saved_data)
@ -432,7 +432,7 @@ def create_user_presences(user_profiles):
# type: (Iterable[UserProfile]) -> None
for user in user_profiles:
status = 1 # type: int
date = timezone.now()
date = timezone_now()
client = get_client("website")
UserPresence.objects.get_or_create(
user_profile=user,