开发者

Launching python within python and timezone issue

I had to make a launcher script for my django app, and it seems it somehow switches the timez开发者_运维技巧one to GMT (default being +2), and every datetime is two hours behind when using the script. What could be causing that?

Here is the launcher script that I use:

#!/usr/bin/env python

import os
import subprocess
import shlex
import time

cwd = os.getcwd()

p1 = subprocess.Popen(shlex.split("python manage.py runserver"),
        cwd=os.path.join(cwd, "drugsworld"))
p2 = subprocess.Popen(shlex.split("python coffee_auto_compiler.py"),
        cwd=os.path.join(cwd))

try:
    while True:
        time.sleep(2)
except KeyboardInterrupt:
    p1.terminate()
    p2.terminate()

If I manually run python manage.py runserver, the timezone is +2. If, however, I use this script, the timezone is set to GMT.


Following up on Robert's idea, you might try adding the env parameter to the Popen call. For example:

import subprocess
p = subprocess.Popen(["date"], env={'TZ':'America/New_York'})
p.wait()
# Fri Jan 14 14:45:44 EST 2011

p = subprocess.Popen(["date"], env={'TZ':'Asia/Taipei'})
p.wait()
# Sat Jan 15 03:45:44 CST 2011


Hmm. Python respects the TZ environment variable... you're not changing it in your script, so it should be equivalent to running it at the shell.

I often set the time zone explicitly. In Django specifically, you can set this in the settings.py file (TIME_ZONE). More general python is:

os.environ['TZ']="America/New_York"
time.tzset()

I imagine if you set the timezone in your settings file, the problem will go away.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜