简体   繁体   English

获取所有可用的时区

[英]Get all available timezones

I'm currently working on an application that is required to support multiple timezones. 我目前正在开发一个支持多个时区所需的应用程序。

For that, I'm using the dateutil library. 为此,我正在使用dateutil库。 Now, I need a way to present the user a list of all available timezones the dateutil library supports. 现在,我需要一种方法向用户显示dateutil库支持的所有可用时区的列表。

Also, is it advisable to store the tz as strings in the database like "Europe/Berlin"? 另外,建议将tz作为字符串存储在数据库中,如“Europe / Berlin”吗?

dateutil will use the OS timezone info, but does carry it's own compressed timezone info file too. dateutil将使用操作系统时区信息,但也会带有自己的压缩时区信息文件。

You could list the available names from the utility code that loads this data: 您可以从加载此数据的实用程序代码中列出可用的名称:

from dateutil.zoneinfo import get_zonefile_instance
zonenames = list(get_zonefile_instance().zones)

You'd need to sort and filter that list a little; 您需要对该列表进行排序和过滤; there are both abbreviated (3 letter) timezone codes as well as "region/city" entries in this list. 此列表中有缩写(3个字母)时区代码以及“region / city”条目。

Storing those names in a database is just fine. 将这些名称存储在数据库中就可以了。

Note that this loads all data into memory; 请注意,这会将所有数据加载到内存中; if that's not desirable you'd need to load the tar file yourself: 如果这不可取,你需要自己加载tar文件:

import os
import tarfile
import dateutil.zoneinfo

zi_path = os.path.abspath(os.path.dirname(dateutil.zoneinfo.__file__))
zonesfile = tarfile.TarFile.open(
    os.path.join(zi_path, dateutil.zoneinfo.ZONEFILENAME))
zonenames = [zn.name for zn in zonesfile.getmembers()
             if not zn.isdir() and zn.name != dateutil.zoneinfo.METADATA_FN]

For dateutil : 对于dateutil

from dateutil.zoneinfo import getzoneinfofile_stream, ZoneInfoFile
ZoneInfoFile(getzoneinfofile_stream()).zones.keys()
>>> ['Asia/Ujung_Pandang',
     'America/Porto_Velho',
     'America/La_Paz',
     'America/Caracas',
     'Europe/Malta',
     'Etc/GMT-13',
     'Atlantic/Bermuda',
     ...]

pytz is a little easier pytz更容易一些

import pytz
pytz.all_timezones
>>> ['Africa/Abidjan',
     'Africa/Accra',
     'Africa/Addis_Ababa',
     'Africa/Algiers',
     'Africa/Asmara',
     'Africa/Asmera',
     'Africa/Bamako',
     'Africa/Bangui',
     'Africa/Banjul',
     'Africa/Bissau',
     'Africa/Blantyre',
     'Africa/Brazzaville',
     ...]

Note that dateutil prefers to use the operating system to determine timezone info. 请注意, dateutil更喜欢使用操作系统来确定时区信息。 pytz uses its own zone files. pytz使用自己的区域文件。 While there are probably advantages to each, pytz provides more consistency if you don't want to manage time zones at the system level. 虽然每个都有可能有优势, pytz如果您不想在系统级别管理时区,则pytz可提供更高的一致性。

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

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