0

As you can see in the title, I want to find the time of given city in Python. How can I achieve this? I've tried geopy and timezonefinder modules but they are giving me different results too. (like 'What time is it in Spotify?', 'It's 12:04')

What I'm trying to achieve is:

What time is it in California?

It's 16:15

THE CODE

import nltk
import datetime
import calendar
import pytz
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder

self.inp = input("City name: ")

# Find city name using NLP
# Get city name
findCityName = str(self.inp.title())
        
# NLP                
word = nltk.word_tokenize(findCityName)
pos_tag = nltk.pos_tag(word)
chunk = nltk.ne_chunk(pos_tag)

self.inp = [ " ".join(w for w, t in ele) for ele in chunk if isinstance(ele, nltk.Tree)]
self.inp = ' '.join(self.inp)

# Get lat, long from city name
geolocator = Nominatim(user_agent='xxx')
location = geolocator.geocode(self.inp.capitalize())

# Get timezone from coordinates
tf = TimezoneFinder()
latitude, longitude = location.latitude, location.longitude

# Timezone
datez = tf.timezone_at(lng=longitude, lat=latitude)
datez = str(datez)
globalDate = datetime.datetime.now(pytz.timezone(datez))

print("The date in " + str(self.inp) + " is: " + globalDate.strftime('%A, %m/%d/%y'))
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • can you post your code and what didn't work? – Narendra Prasath Jun 28 '20 at 13:20
  • This would be a similar article. [Get Timezone from City in Python/Django](https://stackoverflow.com/q/16505501/9014308) – kunif Jun 28 '20 at 13:25
  • It's actually works fine but my problem is when I input something like 'What time is it in Bottle?' it gives me time of Bottle but Bottle isn't a city name. I'm using NLTK for entity recognition. I think the problem is in NLTK code. –  Jun 28 '20 at 13:36
  • It's not similar article. That guy trying to find timezone and publiished code not working at all. –  Jun 28 '20 at 13:37
  • you could also have a look at [tzwhere](https://pypi.org/project/tzwhere/) - however, it seems you need to separate the issues you have with `nltk` (making 'Spotify' a city...) from the unexpected (?) results you get from timezone determination. – FObersteiner Jun 29 '20 at 06:07

0 Answers0