python时区设置——pytz模块

如果你的程序要考虑时区,可以使用pytz。datetime模块中有tzinfo相关的东西,但是它是一个抽象类,文档上说:

tzinfo is an abstract base clase, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module does not supply any concrete subclasses of tzinfo.

上面是说tzinfo是一个抽象类,不应该被直接实例化。你需要派生子类,提供相应的标准方法。datetime模块并不提供tzinfo的任何子类。

所以你可能会使用pytz这个模块。通过easy_install可以安装。目前它的最新文档在这里

关于时区使用的几点想法:

1. 如果你的网站可能有来自其它时区的,可能你要考虑这个问题。都是一个地区的话,还要看服务器是否与用户在一个地区,如果不在,也要考虑。

2. 因此,基本上要考虑服务器时区与用户时区。服务器时区可以配置在系统中,全局生效。而用户时区则与用户相关,可以由用户自已进行设置。

3. 在生成相关时间对象时要加入时区的信息,并在输出时进行合适的转换。

1.Localtime转化为UTC时间

end_time = pytz.UTC.normalize(end_time)

2.从无时区的datetime转换成有时区的(转化后的时间= 原时间 + 时区)

context_tz = pytz.timezone(tz_name)
context_tz.localize(planned_time_no_zone)