简体   繁体   English

时区在python中不可用,但系统时区已正确设置

[英]Timezone not available in python, but the system timezone is properly set

As specified in the documentation : 文档中所述:

%Z -> Time zone name (no characters if no time zone exists).

According to date, my system has the time zone properly set: 根据日期,我的系统正确设置了时区:

gonvaled@pegasus ~ » date
Sat Sep 28 09:14:29 CEST 2013

But this test: 但是这个测试:

def test_timezone():
    from datetime import datetime
    dt = datetime.now()
    print dt.strftime('%Y-%m-%d %H:%M:%S%Z')   
test_timezone()

Produces: 生产:

gonvaled@pegasus ~ » python test_timezone.py 
2013-09-28 09:19:10

Without time zone information. 没有时区信息。 Why is that? 这是为什么? How can I force python to output time zone info? 如何强制python输出时区信息?

I have also trying re-configuring the time zone with tzselect , but has not helped. 我也尝试用tzselect重新配置时区,但没有帮助。

Standard Python datetime.datetime() objects do not have a timezone object attached to them. 标准Python datetime.datetime()对象没有附加时区对象 The system time is taken as is. 系统时间按原样使用。

You'll need to install Python timezone support in the form of the pytz package ; 您需要以pytz的形式安装Python时区支持; timezone definitions change too frequently to be bundled with Python itself. 时区定义变化太频繁,无法与Python本身捆绑在一起。

pytz does not tell you what timezone your machine has been configured with. pytz不会告诉您机器配置的时区。 You can use the python-dateutil module for that; 您可以使用python-dateutil模块 ; it has a dateutil.tz.gettz() function that returns the timezone currently in use. 它有一个dateutil.tz.gettz()函数 ,它返回当前正在使用的时区。 This is much more reliable than what Python can get from the limited C API: 这比Python从有限的C API获得的信息要可靠得多:

>>> import datetime
>>> from dateutil.tz import gettz
>>> datetime.datetime.now(gettz())
datetime.datetime(2013, 9, 28, 8, 34, 14, 680998, tzinfo=tzfile('/etc/localtime'))
>>> datetime.datetime.now(gettz()).strftime('%Y-%m-%d %H:%M:%S%Z')
'2013-09-28 08:36:01BST'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM