如何获取当前时区对应的tz_info对象?
python
(或pytz
)中是否有跨平台函数返回与计算机上当前设置的时区相对应的tzinfo
对象?
不能依赖环境变量,因为它们不是跨平台的
Is there a cross-platform function in python
(or pytz
) that returns a tzinfo
object corresponding to the timezone currently set on the computer?
environment variables cannot be counted on as they are not cross-platform
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
Python 3.7:
Python 3.7:
返回
pytz
时区的tzlocal
模块 适用于* nix 和 win32:注意:它考虑了 DST 和非 DST utc 偏移量变化。
tzlocal
module that returnspytz
timezones works on *nix and win32:Note: it takes into account both DST and non-DST utc offset changes.
time.timezone
返回当前时区偏移量。还有一个datetime.tzinfo
,如果您需要更复杂的结构。time.timezone
returns current timezone offset. there is also adatetime.tzinfo
, if you need more complicated structure.以下代码片段返回不同时区的时间,无论服务器上配置的时区如何。
This following code snippet returns time in a different timezone irrespective of the timezone configured on the server.
我自己没有使用过它,但是 dateutil.tz.tzlocal() 应该可以解决问题。
http://labix.org/python-dateutil#head-50221b5226c3ccb97daa06ea7d9abf0533ec0310
I have not used it myself, but dateutil.tz.tzlocal() should do the trick.
http://labix.org/python-dateutil#head-50221b5226c3ccb97daa06ea7d9abf0533ec0310
也许可以尝试:
import time
print time.tzname
#ortime.tzname[time.daylight]
Maybe try:
import time
print time.tzname
#ortime.tzname[time.daylight]
我问自己同样的问题,我在 [1] 中找到了答案:
看看第 8.1.7 节:格式“%z”(小写,Z 大写也返回时区,但不在 4 -digit 格式,但采用时区缩写的形式,如 [3] 中)的 strftime 返回电子邮件标头中标准的“+/- 4DIGIT”形式(请参阅 RFC 2822 的第 3.3 节,请参阅 [2],该格式已废弃)指定电子邮件标头时区的其他方法)。
因此,如果您希望时区采用这种格式,请使用:
[1] http:// docs.python.org/2/library/datetime.html
[2] https://www.rfc-editor.org/rfc/rfc2822#section-3.3
[3] 时区缩写:http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations ,仅供参考。
I was asking the same to myself, and I found the answer in [1]:
Take a look at section 8.1.7: the format "%z" (lowercase, the Z uppercase returns also the time zone, but not in the 4-digit format, but in the form of timezone abbreviations, like in [3]) of strftime returns the form "+/- 4DIGIT" that is standard in email headers (see section 3.3 of RFC 2822, see [2], which obsoletes the other ways of specifying the timezone for email headers).
So, if you want your timezone in this format, use:
[1] http://docs.python.org/2/library/datetime.html
[2] https://www.rfc-editor.org/rfc/rfc2822#section-3.3
[3] Timezone abbreviations: http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations , only for reference.