You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2021/12/24 07:48:18 UTC

[GitHub] [airflow] Sonins edited a comment on issue #17720: airflow.dates.days_ago doesn't respect configured timezone

Sonins edited a comment on issue #17720:
URL: https://github.com/apache/airflow/issues/17720#issuecomment-1000690305


   I have also same issue. If you would like to open PR, I would like to suggest a little fix in your code.
   The variable that includes user's local time zone already exists as `TIMEZONE` in [settings.py](https://github.com/apache/airflow/blob/main/airflow/settings.py).
   
   ```python
   ...
   # settings.py line 46
   TIMEZONE = pendulum.tz.timezone('UTC')
   try:
       tz = conf.get("core", "default_timezone")
       if tz == "system":
           TIMEZONE = pendulum.tz.local_timezone()
       else:
           TIMEZONE = pendulum.tz.timezone(tz)
   except Exception:
       pass
   ```
   
   And in [timezone.py](https://github.com/apache/airflow/blob/main/airflow/utils/timezone.py), you can get `datetime` object that is set to local timezone.
   
   ```python
   from airflow.settings import TIMEZONE
   ...
   
   # timezone.py line 170
   def datetime(*args, **kwargs):
       """
       Wrapper around datetime.datetime that adds settings.TIMEZONE if tzinfo not specified
       :return: datetime.datetime
       """
       if 'tzinfo' not in kwargs:
           kwargs['tzinfo'] = TIMEZONE
   
       return dt.datetime(*args, **kwargs)
   ```
   
   So you can simply go like this.
   
   ```python
   # dates.py
   from airflow.utils import timezone
   ...
   
   def days_ago(n, hour=0, minute=0, second=0, microsecond=0):
     today = timezone.datetime().now().replace(hour=hour, minute=minute, second=second, microsecond=microsecond)
     return today - timedelta(days=n)
   ```
   
   + This code will emit some error. But you can still make use of `TIMEZONE` and `timezone.datetime()`.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org