Skip to content

CELERY_TIMEZONE and CELERY_ENABLE_UTC have no effect #2649

Closed

Description

@lonemc

I am trying to run a celery worker from console with a timezone different than the local timezone with no luck. No matter what I do, the logs of the worker are always shown with the local timezone (which is not UTC). Shouldn't the worker start by default in the UTC timezone? (assuming the CELERY_ENABLE_UTC is enabled by default).

Here's one possible cause: I vaguely remember this was working a few months ago, so might it be because now the Daylight Saving Time is active?

My real problem is that I have a Django app using the local timezone (which is not UTC), and a few celery tasks inside the Django app. I need those tasks to be run as celery workers that are using the UTC timezone.

Activity

  1. jackyfkc commented on Jun 11, 2015

    @jackyfkc

    The directives CELERY_TIMEZONE and CELERY_ENABLE_UTC are worked for celery beat, not worker.

    The logging in celery does not take into account CELERY_ENABLE_UTC, it just a simple wrapper to python logging module.

  2. thedrow commented on Jun 19, 2015

    @thedrow
    Contributor

    CELERY_ENABLE_UTC is not enabled by default because people might use very old Django versions (below 1.4).
    Can you please provide an example?

  3. malinoff commented on Jun 19, 2015

    @malinoff
    Contributor

    @thedrow just to note, we should enable UTC by default in October, when Django 1.4 LTS support will be ended (https://www.djangoproject.com/download/)

  4. thedrow commented on Jun 19, 2015

    @thedrow
    Contributor

    Yes we probably should do it for 3.2.0.

  5. thedrow commented on Jul 11, 2015

    @thedrow
    Contributor

    Now that I checked the documentation I saw that CELERY_ENABLE_UTC is enabled by default so I think this bug is only related to logging.

  6. ask commented on Jun 24, 2016

    @ask
    Contributor

    Closing this, as we don't have the resources to complete this task.

    May be fixed in master, let's see if comes back after 4.0 release.

  7. mihai-carneylabs commented on Jul 15, 2016

    @mihai-carneylabs

    As a helpful note for anyone who may stumble on this discussion, I was able to run my celery workers on a different timezone (UTC) than the Django project (EST). I gave celery a different Django settings file (i.e. celery_settings), in which I just import the original settings (from settings import *) and then overwrite the TIME_ZONE parameter.

  8. marvelph commented on Jul 16, 2017

    @marvelph

    It seems that this problem still remains in Celery 4.0.2.
    The time stamp of the standard output log is affected by Django's TIME_ZONE parameter.

  9. reopened this on Jul 16, 2017
  10. georgepsarakis commented on Jul 16, 2017

    @georgepsarakis
    Contributor

    Issue #4006 suggests the opposite. @marvelph this may be fixed in current master.

  11. marco-silva0000 commented on Jul 28, 2017

    @marco-silva0000

    I had problems with CELERY_TIMEZONE = 'Europe/Lisbon' and django TIMEZONE = 'Europe/Lisbon' using the beat scheduler. it would wrongly calculate the dates date of the next is_due.
    On the pip version I had the calculation be negative and that would lunch tasks imediatly for ever, on the current master i had it calculate to 1h+repeat time.
    setting both settings to 'UTC' fixes the problem.

  12. georgepsarakis commented on Jul 29, 2017

    @georgepsarakis
    Contributor

    We merged #4173 to master. If you can use the master branch and check if the issue remains, it would be great, thanks.

  13. marco-silva0000 commented on Jul 29, 2017

    @marco-silva0000

    I tested with master, please see the latest comment here #4041
    There is still a problem with celery timezone on the latest master, if I have both CELERY_TIMEZONE and TIMEZONE to 'Europe/Lisbon' the django celery beat schedules the next task to 1h more than the correct time

  14. Ken4scholars commented on Sep 29, 2017

    @Ken4scholars

    I have both TIME_ZONE and CELERY_TIMEZONE set to Europe/Moscow in my project but Celery beat still uses UTC. I've also tried switching the CELERY_ENABLE_UTC setting but nothing changed. My system time is Europe/Moscow and this is really frustrating

  15. 4 remaining items

  16. Jamim commented on Dec 6, 2017

    @Jamim
    Contributor

    As far as I know this issue was fixed in master few months ago. I used master branch pinned to be55de6 instead of release to avoid this and it worked as expected.
    So, it's a great question why is it still not released? It's incomprehensible.

  17. thedrow commented on Dec 6, 2017

    @thedrow
    Contributor

    @Jamim We have a few more pull requests to merge before releasing. See the milestone.

  18. added this to the v4.2 milestone on Dec 19, 2017
  19. auvipy commented on Jan 13, 2018

    @auvipy
    Member
  20. zhangchmeng commented on Apr 19, 2018

    @zhangchmeng

    set timezone 'Asia/Shanghai'.The runtime calculates the correct time,but When retry is enabled eta don't calculate '+' behind time. like this '''ETA:[2018-04-19 11:14:53.216361+08:06] ''''.Only the calculation sheet is not used.I'm going to add the number of seconds to the given time. He works,But what's not perfect?I hope my statement is useful.

  21. kylebebak commented on May 1, 2018

    @kylebebak

    @auvipy
    It's obvious this should not have been closed.

    I'm running celery==4.1.0 and Django==1.11.6.

    Regardless of what I set for CELERY_TIMEZONE and TIMEZONE, Celery beat uses UTC. No combination of True and False for CELERY_ENABLE_UTC and USE_TZ makes a difference.

    It would be better to acknowledge this a bug than make users think it works.

  22. auvipy commented on May 16, 2018

    @auvipy
    Member

    try 4.2rc2 and report please

  23. trianglesis commented on Jun 22, 2018

    @trianglesis

    I can't understand what is going on with time settings in Celery, but I fixed
    base.py -> now
    And now it report actual time for selected timezone 'Europe/London', see log:

    [2018-06-22 13:24:37,338: ERROR/MainProcess] <=Celery App Base=> now -> now_in_utc                      2018-06-22 12:24:37.336361+00:00
    [2018-06-22 13:24:37,338: INFO/MainProcess] <=Celery App Base=> now -> self.timezone                    Europe/London
    [2018-06-22 13:24:37,338: ERROR/MainProcess] <=Celery App Base=> now -> now_in_utc.astimezone(self.timezone)                            2018-06-22 13:24:37.336361+01:00
    [2018-06-22 13:24:37,338: ERROR/MainProcess] <=Celery Schedules=> now -> self.app.now() 2018-06-22 13:24:37.336361+01:00
    [2018-06-22 13:24:37,338: ERROR/MainProcess] <=Utils Time=> remaining -> now 2018-06-22 13:24:37.338674+01:00
    [2018-06-22 13:24:42,349: ERROR/MainProcess] <=Celery Schedules=> now -> self.nowfun() 2018-06-22 13:24:42.349524+01:00
    

    But task is still show time as raw UTC - 2018-06-22 12:24:42.350384

    Test change:

    [2018-06-22 13:40:30,568: ERROR/MainProcess] <=Celery App Base=> timezone_func conf.timezone: Europe/Kiev
    [2018-06-22 13:40:30,569: ERROR/MainProcess] <=Celery App Base=> timezone_func timezone.get_timezone(conf.timezone): Europe/Kiev
    
    [2018-06-22 13:40:30,603: ERROR/MainProcess] <=Celery App Base=> now -> now_in_utc.astimezone(self.timezone) 1                          2018-06-22 15:40:30.600489+03:00
    [2018-06-22 13:40:30,603: ERROR/MainProcess] <=Celery Schedules=> now -> self.app.now() 2018-06-22 15:40:30.600489+03:00
    [2018-06-22 13:40:30,604: ERROR/MainProcess] <=Utils Time=> remaining -> now 2018-06-22 15:40:30.603985+03:00
    [2018-06-22 13:40:30,604: ERROR/MainProcess] <=Celery Schedules=> now -> self.nowfun() 2018-06-22 15:40:30.604436+03:00
    

    So seems like now settings timezone have effect, BUT tasks are still using an UTC time!

  24. trianglesis commented on Jun 22, 2018

    @trianglesis

    Firstly, this probably should be the datetime.now instance, not datetime.utcnow(), because why would we decide to UTC already an UTC?

    def to_utc(dt):
        """Convert naive :class:`~datetime.datetime` to UTC."""
        return make_aware(dt, timezone.utc)
    

    It now allows me to set London time everywhere:

    <=Celery App Base=> timezone_func conf.timezone: Europe/London
    <=Celery App Base=> timezone_func timezone.get_timezone(conf.timezone): Europe/London
    <=Celery Schedules=> now -> self.nowfun() 2018-06-22 14:11:03.625825+01:00
    <=Utils Time=> to_utc -> What is dt_utc: 2018-06-22 14:11:03.626616
    <=Utils Time=> remaining -> now 2018-06-22 14:11:03.629900+01:00
    <=Celery Schedules=> now -> self.nowfun() 2018-06-22 14:11:03.630299+01:00
    
    <=Utils Time=> make_aware -> _localize(dt, is_dst=None) 2018-06-22 14:11:03.630514+00:00
    <=Utils Time=> to_utc -> make_aware(dt_utc, timezone.utc): 2018-06-22 14:11:03.630514+00:00
    <=Utils Time=> make_aware -> What is dt: 2018-06-22 14:11:03.630514
    

    But still task recieved in older time:

    Received | 2018-06-22 13:05:02.712443 UTC
    -- | --
    Sent | 2018-06-22 13:05:02.707066 UTC
    Started | 2018-06-22 13:05:02.716835 UTC
    Succeeded | 2018-06-22 13:05:03.029372 UTC
    Retries | 0
    Timestamp | 2018-06-22 13:05:03.029372 UTC
    
  25. georgepsarakis commented on Jun 22, 2018

    @georgepsarakis
    Contributor

    @trianglesis if possible, please open a PR with your changes and we can discuss it there.

  26. qburst-starsona commented on Aug 30, 2018

    @qburst-starsona
  27. liziwl commented on Oct 19, 2019

    @liziwl

    I have the same problem that date_done always using UTC when I have set

    cel_app.conf.timezone = 'Asia/Shanghai'
    cel_app.conf.enable_utc = True

    on v4.3.0 installed by pip and redis, so the problem is fixed or not?

  28. w4230213 commented on Feb 9, 2023

    @w4230213

    I got the similar problem on v5.2.3, the "date_done" record in result end was always UTC time, no matter what setting in celeryconfig.py, after some digging, here's the reason and the work round:

    • REASON: I'm using Mongo as my backend, the "date_done" is generate in a method: _get_result_meta(), provided by the default MongoBackend, well, acutally, it's in the super class of MongoBackend: celery.backend.base: Backend. So look into the code, you'll find this line:
      _date_done = datetime.utcnow()_
      And no other codes for tz convert, that's the reason.

    • SOLUTION: I just create a new subclass of the default MongoBackend, and override the method: _get_result_meta(), add some real timezone convertion logic at the last:

    class MyMongoBackend(celery.backends.mongodb.MongoBackend):
        ...
        ...
        def _get_result_meta(self, result, state, traceback, request, format_date=True, encode=False):
            origin_meta = super()._get_result_meta(result, state, traceback, request, format_date, encode)
            # tz convert
            if self.app.conf.timezone is not None:
                local_dt = convert_timezone(origin_meta['date_done'], tz=self.app.conf.timezone)
                origin_meta['date_done'] = local_dt
            return origin_meta
    

    Just for consideration:

    def convert_timezone(origin_dt, tz='Asia/Shanghai', fmt="%Y-%m-%dT%H:%M:%S.%f"):
     
        as_string = False
        if isinstance(origin_dt, str):
            as_string = True
            origin_dt = datetime.datetime.strptime(origin_dt, fmt)
        origin_dt = origin_dt.replace(tzinfo=datetime.timezone.utc)
        target_tz = pytz.timezone(tz)
        converted_dt = origin_dt.astimezone(target_tz)
        if as_string:
            return converted_dt.strftime(fmt)
        else:
            return converted_dt
    
    import celery
    import my_mongo_backend
    
    app = celery.Celery()
    app.backend_cls = 'my_mongo_backend.MyMongoBackend'
    
  29. Cherrymelon commented on Nov 19, 2024

    @Cherrymelon

    @w4230213 thank for your patch code, I adjusted it and work well for my mysql db.

    app.conf.update(
        ...,
        override_backends={"db": "celery_task.patch_timezone.MyBackend"},
    )
    

    and this is my mysql class code:

    import datetime
    from typing import override
    import pytz
    from celery.backends.database import DatabaseBackend
    
    
    def convert_timezone(origin_dt, tz='Asia/Shanghai', fmt="%Y-%m-%dT%H:%M:%S.%f"):
        as_string = False
        if isinstance(origin_dt, str):
            as_string = True
            origin_dt = datetime.datetime.strptime(origin_dt, fmt)
        origin_dt = origin_dt.replace(tzinfo=datetime.timezone.utc)
        target_tz = pytz.timezone(tz)
        converted_dt = origin_dt.astimezone(target_tz)
        if as_string:
            return converted_dt.strftime(fmt)
        else:
            return converted_dt
    
    
    class MyBackend(DatabaseBackend):
    
        @override
        def _get_result_meta(self, result,
                             state, traceback, request, format_date=True,
                             encode=False):
            origin_meta = super()._get_result_meta(result,
                                                   state, traceback, request, format_date, encode)
            # tz convert
            if self.app.conf.timezone is not None and origin_meta['date_done'] is not None:
                local_dt = convert_timezone(origin_meta['date_done'], tz=self.app.conf.timezone)
                origin_meta['date_done'] = local_dt
            return origin_meta
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions