django - Celery beat_schedule 使用了错误的时区
问题描述
我正在尝试使用 celery beat 将日常任务作为我的 Django Web 应用程序的一部分运行,它调用一个带有日期字符串参数的函数。节拍时间表工作正常,并且每天在正确的时间调用该函数,但输入到该函数的日期字符串总是晚一天。我认为这是因为时区设置错误,但我认为我已经正确配置了 Django 和 celery,所以我看不出问题出在哪里。
中的相关设置./settings.py
:
TIME_ZONE = 'Europe/London'
USE_TZ = True
CELERY_ENABLE_UTC = False
CELERY_TIMEZONE = TIME_ZONE
我的芹菜配置./my_project/celery.py
:
from django.utils import timezone
from celery import Celery
from celery.schedules import crontab
app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
# Configure daily tasks
app.conf.beat_schedule = {
# Executes `my_task` every day at 10:00am
'do-my-task': {
'task': 'tasks.tasks.my_task',
'schedule': crontab(minute=0, hour=10),
'args': (timezone.now().strftime('%d/%m/%Y'), ),
},
}
有什么想法为什么应该输入错误的日期字符串作为参数my_task
?
解决方案
django.utils.timezone.now
不做你认为它做的事。 根据文档,它将返回 UTC 时间,时区设置为 UTC。它不会Europe/London
按照您的意愿返回时间:
如果
USE_TZ
是True
,这将是一个感知datetime
的,以 UTC 表示当前时间。请注意,now()
无论 ; 的值如何,都将始终返回 UTC 时间TIME_ZONE
。您可以使用localtime()
获取当前时区的时间。
正如文档建议的那样,使用localtime
而不是now
.
推荐阅读
- machine-learning - Julia ML:是否有推荐的数据格式用于将数据加载到 Flux、Knet、深度学习库
- python - 在特定范围的索引上迭代列表并获取这些索引中子列表的元素
- c++ - 当我尝试读取 .txt 文件时,Xcode 冻结
- tensorflow - 在 keras 中微调 InceptionV3 模型
- ios - 半透明导航栏在调用时表现异常
- safari - 我可以使用 http(s) 从 icloud 下载 Safari 书签吗?
- flutter - 如何防止用户更改设置的 TextEditingController 文本?
- python - seaborn 散点图绘制的日期比原始数据中的日期多
- java - 如何找到一个没有数字出现多次的数字(J3 CCC 2013 从 1987 年到 2013 年)
- python - Python monkeypatch.setattr() 在模块范围内带有 pytest 夹具