python APScheduler timezone问题和linux系统环境timezone不对称报错

运行python报错ValueError: Timezone offset does not match system offset: 28800 != 0. Please, check your config files.

首先,我们可以看看源码lib/python2.7/site-packages/tzlocal/utils.py

# -*- coding: utf-8 -*-
import time
import datetime
import calendar


def get_system_offset():
    """Get system's timezone offset using built-in library time.

    For the Timezone constants (altzone, daylight, timezone, and tzname), the
    value is determined by the timezone rules in effect at module load time or
    the last time tzset() is called and may be incorrect for times in the past.

    To keep compatibility with Windows, we're always importing time module here.
    """

    localtime = calendar.timegm(time.localtime())
    gmtime = calendar.timegm(time.gmtime())
    offset = gmtime - localtime
    # We could get the localtime and gmtime on either side of a second switch
    # so we check that the difference is less than one minute, because nobody
    # has that small DST differences.
    if abs(offset - time.altzone) < 60:
        return -time.altzone
    else:
        return -time.timezone


def get_tz_offset(tz):
    """Get timezone's offset using built-in function datetime.utcoffset()."""
    return int(datetime.datetime.now(tz).utcoffset().total_seconds())


def assert_tz_offset(tz):
    """Assert that system's timezone offset equals to the timezone offset found.

    If they don't match, we probably have a misconfiguration, for example, an
    incorrect timezone set in /etc/timezone file in systemd distributions."""
    tz_offset = get_tz_offset(tz)
    system_offset = get_system_offset()
    if tz_offset != system_offset:
        msg = ('Timezone offset does not match system offset: {0} != {1}. '
               'Please, check your config files.').format(
                   tz_offset, system_offset
               )
        raise ValueError(msg)

可以看到“28800”获取的是APScheduler的默认timezone,而“0”是获取的系统环境变量的TZ时间

28800对应timezone为“Asia/Shanghai”, 而0对应timezone为“UTC”。

解决:

from flask_apscheduler import APScheduler
from apscheduler.schedulers.background import BackgroundScheduler

import os

# 设置系统环境变量的timezone 

os.environ['TZ']= "Asia/Shanghai"   

# 设置APScheduler注册的timezone

scheduler = APScheduler(BackgroundScheduler(timezone="Asia/Shanghai"))

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值