Skip to content

Timezone calculations in app.now() are incorrect #4160

Closed

Description

@rtpg

From celery/app/base.py


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

This is just semantically wrong. This takes the UTC timezone-aware time and replaces the timezone, without actually ensuring it's the same point in time.

So 9 AM UTC becomes 9 AM JTC, even though 9 AM UTC is 6 PM JTC

The "proper" way of doing this is self.timezone.normalize(datetime.utcnow())

This bug breaks things like crontab for celery beat, for example, since the schedules get shifted around. And it's the wrong time too

Activity

  1. changed the title [-]Timezone calculaitons are incorrect[/-] [+]Timezone calculations in app.now() are incorrect[/+] on Jul 26, 2017
  2. georgepsarakis commented on Jul 26, 2017

    @georgepsarakis
    Contributor

    This may be caused by the changes in this Pull Request.

  3. georgepsarakis commented on Jul 26, 2017

    @georgepsarakis
    Contributor

    Perhaps also related: #4145

  4. georgepsarakis commented on Jul 26, 2017

    @georgepsarakis
    Contributor

    @rtpg Based on your suggestion, I think this might be the correct implementation:

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

    I need to test it some more though.

  5. rtpg commented on Jul 27, 2017

    @rtpg
    Author

    one detail (I'm not sure how it applies here, but it feels relevant) is whether self.timezone differs from the system timezone.

    For example if self.timezone is UTC+1 but the system timezone is UTC+9

    If those differs, then datetime.utcnow() will return the current timestamp (probably) by subtracting 9 hours from the now, but then self.timezone.normalize(now_in_utc) will shift it forward by only 1 hour?

    Though..... maybe the system timezone is "always right". This might be ramblings based off of imprecise understanding of this

  6. georgepsarakis commented on Jul 27, 2017

    @georgepsarakis
    Contributor

    @rtpg I think it is actually the other way round, the system clock counts in UTC (Universal Coordinated Time) and when you set the system timezone, it changes the representation only. Thus UTC is an absolute measure of time, whereas timezones are relative offsets to UTC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions