Is there a way to get locale from country or timezone?

戏子无情 提交于 2019-12-22 09:37:50

问题


I was programming a program in Python, where I need to output date as per user's locale:

  1. Get a list of timezones in a country specified as per user input (did that using pytz)
  2. Get the locale of the user (which I am unable to figure out how to do)

Is there a way to get locale from county/timezone or some other method needs to be followed?

Or do I need to get the locale input from user itself?

EDIT

The program is to be a web-app. The user can provide me his country. But does he have to explicitly provide me the locale also or can I get it from his timezone/country?


回答1:


I don't think it's possible to convert country + timezone into a single 'correct' locale... in countries with multiple languages there is not a 1:1 relation between language and timezone.

The closest I can see is to use Babel:

from babel import Locale
Locale.parse('und_BR')  # 'und' here means unknown
>>> Locale('pt', territory='BR')

This gives you a single 'most likely' (or default) locale for the country. To handle the languages properly you need to ask the user their preferred language.




回答2:


Use pycountry to do this.

sudo pip install pycountry


来源:https://stackoverflow.com/questions/9839227/is-there-a-way-to-get-locale-from-country-or-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!