Reputation: 21
Is there any option better and faster than this code below that I am using to get the name of the Country from the name of a City! So I'm trying to get for example from a Timezone (Europe/Istanbul) to get in the end ๐น๐ทTurkey/TR or to convert a Timezone (Europe/Berlin) to a Country Code (DE) and after from the (DE) to convert to ๐ฉ๐ชGermany/DE, so all I want is... no matter which TIMEZONE
will be, at the end to give me always FLAG/COUNTRY/CODE
This code I'm using is 60% okay and slow, but every time when it's London in TIMEZONE I get NONE
results, also I'm getting NONE
results from some others TIMEZONE, not only if it's London!
import pycountry
import geopy
from geopy.geocoders import Nominatim
#Example:
timezone='Europe/London'
try:
city=str(timezone).split('/')[1].replace('/','')
except:pass
vpzip(city)
coun=""
code=""
flag=""
country=""
try:
geolocator=Nominatim(user_agent="location-finder",timeout=3)
location=geolocator.geocode(city, language='en')
countrys=str(location).split(',')[-1].replace(' ','')
countr=pycountry.countries.get(name=countrys)
code=countr.alpha_2
flag=countr.flag
coun=countr.name
country=str(flag)+'/'+str(coun)+'/'+str(code)
except:
country='NONE'
return country
print(vpzip(city))
Thanks in advance to ALL
Upvotes: 1
Views: 188
Reputation: 81
If you are looking for a faster performing code use countrywrangler
instead of pycountry
.
Here is a usage example:
import countrywrangler as cw
timezone='Europe/London'
country_code = cw.Normalize.timezone_to_alpha2(timezone)
print(country_code) # Prints GB
Full documentation: https://countrywrangler.readthedocs.io/en/latest/normalize/timezone/
Disclosure: I am the author of countrywrangler.
Upvotes: 3
Reputation: 120399
It probably doesn't help but if you use Pandas, it can be possible to make the mapping yourself:
import pandas as pd
df1 = pd.read_html('https://en.wikipedia.org/wiki/List_of_tz_database_time_zones')[0].iloc[:, :2]
df1.columns = ['Code', 'Timezone']
df1 = df1.assign(Code=df1['Code'].str.split(',\s*')).explode('Code').dropna()
df2 = pd.read_html('https://en.wikipedia.org/wiki/Regional_indicator_symbol')[0].iloc[:, :3]
df2.columns = ['Flag', 'Code', 'Country']
out = df1.merge(df2, on='Code')
>>> out
Code Timezone Flag Country
0 CI Africa/Abidjan ๐จ๐ฎ Cรดte d'Ivoire
1 BF Africa/Abidjan ๐ง๐ซ Burkina Faso
2 BF Africa/Ouagadougou ๐ง๐ซ Burkina Faso
3 GH Africa/Abidjan ๐ฌ๐ญ Ghana
4 GH Africa/Accra ๐ฌ๐ญ Ghana
.. ... ... ... ...
646 PN Pacific/Pitcairn ๐ต๐ณ Pitcairn Islands
647 CK Pacific/Rarotonga ๐จ๐ฐ Cook Islands
648 WF Pacific/Tarawa ๐ผ๐ซ Wallis & Futuna
649 WF Pacific/Wallis ๐ผ๐ซ Wallis & Futuna
650 TO Pacific/Tongatapu ๐น๐ด Tonga
[651 rows x 4 columns]
Test:
>>> out[out['Timezone']=='Europe/London']
Code Timezone Flag Country
525 GB Europe/London ๐ฌ๐ง United Kingdom
559 GG Europe/London ๐ฌ๐ฌ Guernsey
564 IM Europe/London ๐ฎ๐ฒ Isle of Man
566 JE Europe/London ๐ฏ๐ช Jersey
Upvotes: 3