Spaces:
Runtime error
Runtime error
File size: 6,378 Bytes
e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 66cde78 e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 92ef4cf e26fb90 66cde78 e26fb90 92ef4cf e26fb90 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from datetime import datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import pycountry
from typing import List, Optional
app = FastAPI(
title="Country DateTime API",
description="Get current date and time for any country",
version="1.0.0"
)
# Response models
class TimezoneInfo(BaseModel):
timezone: str = Field(..., description="IANA timezone name")
datetime: str = Field(..., description="Local datetime in YYYY-MM-DD HH:MM:SS format")
utc_offset: str = Field(..., description="UTC offset (e.g., +0530)")
timezone_abbr: str = Field(..., description="Timezone abbreviation (e.g., IST)")
class CountryDateTimeResponse(BaseModel):
country: str = Field(..., description="Full country name")
alpha_2: str = Field(..., description="ISO 3166-1 alpha-2 country code")
datetime_info: List[TimezoneInfo] = Field(..., description="List of timezones with datetime")
class ErrorResponse(BaseModel):
error: str = Field(..., description="Error message")
def get_country_datetime(country_name: str) -> dict:
"""
Gets the current date and time for a given country.
Args:
country_name: The name of the country.
Returns:
A dictionary with country and datetime information.
Raises:
ValueError: If country is not found or has no timezones.
"""
# Find the country
try:
country = pycountry.countries.get(name=country_name)
if not country:
country = pycountry.countries.search_fuzzy(country_name)[0]
except (LookupError, IndexError, AttributeError):
raise ValueError(f"Country '{country_name}' not found.")
# Get timezones for the country
try:
import pytz
timezones = pytz.country_timezones.get(country.alpha_2, [])
if not timezones:
raise ValueError(f"No timezones found for country '{country_name}'.")
except Exception as e:
raise ValueError(f"Error retrieving timezones: {str(e)}")
# Get datetime for each timezone
datetime_info = []
utc_now = datetime.now(ZoneInfo("UTC"))
for tz_name in timezones:
try:
timezone = ZoneInfo(tz_name)
local_time = utc_now.astimezone(timezone)
datetime_info.append({
"timezone": tz_name,
"datetime": local_time.strftime('%Y-%m-%d %H:%M:%S'),
"utc_offset": local_time.strftime('%z'),
"timezone_abbr": local_time.strftime('%Z')
})
except ZoneInfoNotFoundError:
continue
if not datetime_info:
raise ValueError(f"Could not retrieve datetime for any timezone in '{country_name}'.")
return {
"country": country.name,
"alpha_2": country.alpha_2,
"datetime_info": datetime_info
}
@app.get("/", tags=["Info"])
async def root():
"""Root endpoint with API information."""
return {
"message": "Country DateTime API",
"endpoints": {
"GET /datetime/{country_name}": "Get datetime for a specific country",
"GET /datetime": "Get datetime for a country using query parameter",
"GET /docs": "API documentation"
}
}
@app.get(
"/datetime/{country_name}",
response_model=CountryDateTimeResponse,
responses={
200: {"description": "Successful response"},
404: {"model": ErrorResponse, "description": "Country not found"},
500: {"model": ErrorResponse, "description": "Server error"}
},
tags=["DateTime"]
)
async def get_datetime_by_path(country_name: str):
"""
Get current date and time for a country using path parameter.
- **country_name**: Name of the country (e.g., "India", "United States")
"""
try:
result = get_country_datetime(country_name)
return JSONResponse(content=result)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@app.get(
"/datetime",
response_model=CountryDateTimeResponse,
responses={
200: {"description": "Successful response"},
404: {"model": ErrorResponse, "description": "Country not found"},
500: {"model": ErrorResponse, "description": "Server error"}
},
tags=["DateTime"]
)
async def get_datetime_by_query(
country: str = Query(..., description="Name of the country", examples=["India", "United States"])
):
"""
Get current date and time for a country using query parameter.
- **country**: Name of the country (e.g., "India", "United States")
"""
try:
result = get_country_datetime(country)
return JSONResponse(content=result)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
@app.get("/countries", tags=["Info"])
async def list_countries(
search: Optional[str] = Query(None, description="Search term to filter countries")
):
"""
List all available countries or search for specific countries.
- **search**: Optional search term to filter countries
"""
countries = []
for country in pycountry.countries:
if search:
if search.lower() in country.name.lower():
countries.append({
"name": country.name,
"alpha_2": country.alpha_2,
"alpha_3": country.alpha_3
})
else:
countries.append({
"name": country.name,
"alpha_2": country.alpha_2,
"alpha_3": country.alpha_3
})
return {
"total": len(countries),
"countries": countries[:100] if not search else countries
}
@app.get("/health", tags=["Info"])
async def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"timestamp": datetime.now(ZoneInfo("UTC")).isoformat()
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |