如何从python中的tzfile中找到时区名称 [英] How to find the timezone name from a tzfile in python
问题描述
有没有可能得到这个操作的逆:
Is it possible to get the inverse of this operation:
import dateutil.tz
tz_ny = dateutil.tz.tz.gettz('America/New_York')
print(type(tz_ny))
print(tz_ny)
打印:
dateutil.tz.tz.tzfile
tzfile('/usr/share/zoneinfo/America/New_York')
如何在给定 tz_ny 类型的 tzfile 的情况下恢复America/New_York"?
How to recover 'America/New_York' given tz_ny of type tzfile?
注意tz_ny.tzname(datetime.datetime(2017,1,1))
如果日期在夏季,则返回EST"或EDT".
N.B. tz_ny.tzname(datetime.datetime(2017,1,1))
return 'EST' or 'EDT' if the date is in the summer.
推荐答案
如果您只想要 tzfile
中的时区名称而不是完整路径,您可以例如做
If you want just the timezone name from a tzfile
and not the full path, you can e.g. do
import dateutil.tz
tz_ny = dateutil.tz.tz.gettz('America/New_York')
tz_ny_zone= "/".join(tz_ny._filename.split('/')[-2:])
print(tz_ny_zone)
让你得到
'America/New_York'
EDIT:为了完整起见,由于标题只提到了 tzfile
:除了 dateutil
之外,还有其他可以使用的模块获取 tzfile
.一种方法是使用 pytz
模块中的 timezone()
:
EDIT: Just for the sake of completeness, since the title only mentions tzfile
: Besides dateutil
there are other modules which can be used to get a tzfile
. One way is using timezone()
from the pytz
module:
import pytz
tz_ny_pytz = pytz.timezone('America/New_York')
根据您最初使用的模块,tzfile
的类有所不同
Depending on which module you used in the first place, the class of tzfile
differs
print(type(tz_ny))
print(type(ty_ny_pytz))
印刷品
<class 'dateutil.tz.tz.tzfile'>
<class 'pytz.tzfile.America/New_York'>
对于 pytz
对象,有一种更直接的方式以人类可读的形式访问时区,使用 .zone
属性:
For the pytz
object, there is a more direct way of accessing the timezone in human readable form, using the .zone
attribute:
print(tz_ny_pytz.zone)
生产
'America/New_York'
这篇关于如何从python中的tzfile中找到时区名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!