Hi everyone, I'm going to show you how to create a simple web app in python that will retrieve time in any city in the world.
First we need to make sure that python is installed you can visit their website for how to install it (https://www.python.org/downloads/windows/)
Then make sure to install Flask to run your app on the web you can install it by opening a command prompt or Powershell in Window and run this command:
pip install flask
And then to ensure that the app can retrieve any city we need to install this library with this command:
pip install geopy timezonefinder pytz
Then create a folder named time for example you can choose any name and inside it create a file named app.py you can do that by right click anywhere in the empty space inside the folder you created and choose text file then name it to app.py with then open it in text editor I use notepad++ you can download it from this link
(https://notepad-plus-plus.org/downloads/)
Here is the code you need to copy it and paste it inside app.py file:
from flask import Flask, request, render_template_string
from datetime import datetime
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
import pytz
app = Flask(__name__)
# HTML template
html_template = """
<!DOCTYPE html>
<html>
<head>
<title>City Time Zone</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
text-align: center;
background: #ffffff;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
width: 400px;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
form {
margin-bottom: 20px;
}
input[type="text"] {
padding: 10px;
font-size: 16px;
width: calc(100% - 24px);
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #007BFF;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.error {
color: red;
margin-top: 10px;
}
.time {
margin-top: 20px;
font-size: 18px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Enter a City to Get the Current Time</h1>
<form method="post">
<input type="text" id="city" name="city" placeholder="Enter city name" required>
<button type="submit">Get Time</button>
</form>
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
{% if time %}
<p class="time">The current time in {{ city }} is: {{ time }}</p>
{% endif %}
</div>
</body>
</html>
"""
@app.route('/', methods=['GET', 'POST'])
def index():
error = None
current_time = None
city = None
if request.method == 'POST':
city = request.form.get('city')
if city:
city = city.strip()
try:
# Geocode the city to get latitude and longitude
geolocator = Nominatim(user_agent="timezone_app")
location = geolocator.geocode(city)
if not location:
raise ValueError("City not found. Please check the spelling or try another city.")
# Find the timezone based on latitude and longitude
tf = TimezoneFinder()
timezone_name = tf.timezone_at(lng=location.longitude, lat=location.latitude)
if not timezone_name:
raise ValueError("Could not determine the timezone for this location.")
# Get the current time in the timezone
timezone = pytz.timezone(timezone_name)
current_time = datetime.now(timezone).strftime('%Y-%m-%d %H:%M:%S')
except Exception as e:
error = str(e)
else:
error = "City name cannot be empty."
return render_template_string(html_template, error=error, time=current_time, city=city)
if __name__ == '__main__':
app.run(debug=True)
Now your app is almost ready one final step is to start it by using this command in command prompt or Powershell remember you have to navigate to the exact location of your folder and be inside it when you run this command:
python app.py
Then open up a web browser and type in the address field:
localhost:5000
I hope you like it thank you so much and enjoy.
Top comments (0)