Je pense que le mieux est de passer en revue tous les fuseaux horaires de pytz et de vérifier lequel correspond au fuseau horaire local, chaque objet de fuseau horaire de pytz contient des informations sur l'utcoffset et le tzname comme CDT, EST, les mêmes informations sur l'heure locale peuvent être obtenues à partir de time.timezone/altzone
y time.tzname
et je pense que c'est suffisant pour faire correspondre correctement le fuseau horaire local dans la base de données pytz, par exemple.
import time
import pytz
import datetime
local_names = []
if time.daylight:
local_offset = time.altzone
localtz = time.tzname[1]
else:
local_offset = time.timezone
localtz = time.tzname[0]
local_offset = datetime.timedelta(seconds=-local_offset)
for name in pytz.all_timezones:
timezone = pytz.timezone(name)
if not hasattr(timezone, '_tzinfos'):
continue#skip, if some timezone doesn't have info
# go thru tzinfo and see if short name like EDT and offset matches
for (utcoffset, daylight, tzname), _ in timezone._tzinfos.iteritems():
if utcoffset == local_offset and tzname == localtz:
local_names.append(name)
print local_names
sortie :
['Amérique/Atikokan', 'Amérique/Bahia_Banderas', 'America/Bahia_Banderas', 'America/Belize', 'America/Cambridge_Bay', 'America/Cancun', 'America/Chicago', 'America/Chihuahua', "America/Coral_Harbour", "America/Costa_Rica", "America/El_Salvador", "America/Fort_Wayne", "America/Guatemala", "Amérique/Indiana/Indianapolis", "Amérique/Indiana/Knox", America/Indiana/Marengo", "America/Indiana/Marengo", America/Indiana/Petersburg", "America/Indiana/Tell_City", "America/Indiana/Vevay", "America/Indiana/Vincennes", America/Indiana/Winamac", "America/Indianapolis", "America/Iqaluit", "America/Kentucky/Louisville", "America/Kentucky/Louisville", "America/Kentucky/Monticello", "America/Knox_IN", "America/Louisville", "America/Louisville", "America/Managua", "America/Matamoros", "America/Menominee", "America/Merida", "America/Mexico_City", "America/Monterrey", Amérique/Dakota du Nord/Beulah, Amérique/Dakota du Nord/Centre, "America/North_Dakota/New_Salem", "America/Ojinaga", "America/Pangnirtung", "America/Rainy_River", "America/Rankin_Inlet", America/Resolute", "America/Resolute", "America/Tegucigalpa", America/Winnipeg', 'CST6CDT', 'Canada/Central', 'Mexico/General', US/Central', 'US/East-Indiana', 'US/Indiana-Starke']
En production, vous pouvez créer un tel mappage à l'avance et le sauvegarder au lieu de toujours itérer.
Test du script après le changement de fuseau horaire :
$ export TZ='Australia/Sydney'.
$ python get_tz_names.py
["Antarctique/Macquarie", "Australie/ACT", "Australie/Brisbane", Australie/Canberra", "Australie/Currie", "Australie/Hobart", Australie/Lindeman", "Australie/Melbourne", "Australie/NSW", Australie/Queensland", "Australie/Sydney", "Australie/Tasmanie", Australie/Victoria]