I'm creating a website with Flask and want to show a live clock with the time in different cities. I have longitude and latitude stored in my database for every city. Using geonames plugin I'm able to get timezoneid by coordinates.
Example:
import geonames
geonames_client = geonames.GeonamesClient('demo')
geonames_result = geonames_client.find_timezone({'lat': 48.871236, 'lng': 2.77928})
print geonames_result['timezoneId']
Output:
'Europe/Paris'
How can I display a live clock on my page?
Example:
Current time in the city: 12:59
UPD: Figured out how to show the live time knowing the timezone with javascript thanks to @Matt:
<script type='text/javascript'>
function update() {
$('#clock').html(moment().tz("{{timezone}}").format('H:mm:ss'));
}
setInterval(update, 1000);
</script>
Now, I'm having another problem - I cannot get the timezone id by coordinates.Line "geonames.GeonamesClient('username')" does not work for some reason. I read result['Lat'] and result['Lng'] from my database.
import geonames
try:
location = {}
location['lat'] = result['Lat']
location['lng'] = result['Lng']
geonames_client = geonames.GeonamesClient('username')
print "test"
geonames_result = geonames_client.find_timezone(location)
print geonames_result['timezoneId']
result['Timezone'] = geonames_result['timezoneId']
except:
result['Timezone'] = 'America/Los_Angeles'
So, I'm constantly getting the except value.
I am using Flask + virtualenv + uwsgi + Nginx
UPD2: I managed to do it. I am reading from mysql database lat and lng of the city and city's timezone, if timezone is not specified - I make a request to geonames.org and get the timezone id by the long and lat and write it to my database, so I don't need to request next time. Then I send the timezone id to the Jinja2 template. And using moment.js and moment-timezone display the current time in the city. You can see the updated page (clear the cache first): [link]test.fantazia-svit.com.ua/city/9
In order to get timezone from geonames I use this function:
import urllib
import json
try:
url = "http://api.geonames.org/timezoneJSON?lat=%s&lng=%s&username=%s" % (Lat, Lng, username)
response = urllib.urlopen(url);
data = json.loads(response.read())
Timezone = data['timezoneId']
except:
Timezone = ''
Where Lat = your latitude, Lng = longitude and username = your username in genomes.org