Skip to content

Commit

Permalink
Correct calculation of application current time with timezone (celery…
Browse files Browse the repository at this point in the history
…#4173)

* Use datetime.astimezone to adjust current time

* Remove import statements from Celery.now
  • Loading branch information
georgepsarakis authored and Cesar Canassa committed Aug 21, 2017
1 parent d53f0f1 commit 60cc995
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
7 changes: 5 additions & 2 deletions celery/app/base.py
Expand Up @@ -2,6 +2,7 @@
"""Actual App instance implementation."""
from __future__ import absolute_import, unicode_literals

from datetime import datetime
import os
import threading
import warnings
Expand Down Expand Up @@ -37,6 +38,8 @@
from celery.utils.dispatch import Signal
from celery.utils.functional import first, maybe_list, head_from_fun
from celery.utils.time import timezone
from celery.utils.time import timezone, \
get_exponential_backoff_interval, to_utc
from celery.utils.imports import gen_task_name, instantiate, symbol_by_name
from celery.utils.log import get_logger
from celery.utils.objects import FallbackContext, mro_lookup
Expand Down Expand Up @@ -870,8 +873,8 @@ def prepare_config(self, c):

def now(self):
"""Return the current time and date as a datetime."""
from datetime import datetime
return datetime.utcnow().replace(tzinfo=self.timezone)
now_in_utc = to_utc(datetime.utcnow())
return now_in_utc.astimezone(self.timezone)

def select_queues(self, queues=None):
"""Select subset of queues.
Expand Down
9 changes: 5 additions & 4 deletions t/unit/app/test_app.py
Expand Up @@ -79,10 +79,10 @@ def test_now(self):
tz_utc = timezone.get_timezone('UTC')
tz_us_eastern = timezone.get_timezone(timezone_setting_value)

now = datetime.utcnow().replace(tzinfo=tz_utc)
now = to_utc(datetime.utcnow())
app_now = self.app.now()

assert app_now.tzinfo == tz_utc
assert app_now.tzinfo is tz_utc
assert app_now - now <= timedelta(seconds=1)

# Check that timezone conversion is applied from configuration
Expand All @@ -92,7 +92,8 @@ def test_now(self):
del self.app.timezone

app_now = self.app.now()
assert app_now.tzinfo == tz_us_eastern

assert app_now.tzinfo.zone == tz_us_eastern.zone

diff = to_utc(datetime.utcnow()) - localize(app_now, tz_utc)
assert diff <= timedelta(seconds=1)
Expand All @@ -102,7 +103,7 @@ def test_now(self):
del self.app.timezone
app_now = self.app.now()
assert self.app.timezone == tz_us_eastern
assert app_now.tzinfo == tz_us_eastern
assert app_now.tzinfo.zone == tz_us_eastern.zone

@patch('celery.app.base.set_default_app')
def test_set_default(self, set_default_app):
Expand Down

0 comments on commit 60cc995

Please sign in to comment.