Skip to content

Instantly share code, notes, and snippets.

@Jawschamp
Created December 14, 2024 00:24
Show Gist options
  • Save Jawschamp/436d48e8eaccb2715a6ef97571db61a8 to your computer and use it in GitHub Desktop.
Save Jawschamp/436d48e8eaccb2715a6ef97571db61a8 to your computer and use it in GitHub Desktop.
from sanic import Sanic, Request
from sanic.response import json
from datetime import datetime
import pytz # For timezone handling
app = Sanic(__name__)
# Function for ordinal numbers
def p_ordinal(n):
if 11 <= (n % 100) <= 13:
suffix = 'th'
else:
suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')
return str(n) + suffix
def format_date(date_str, timezone="UTC"):
try:
# Split the date string to remove microseconds if present
date_str_parts = date_str.split('.')
date_str = date_str_parts[0] # Use only the part before the decimal point
# Parse the date as a naive datetime object (no timezone info)
naive_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
# Assuming the input is in UTC, we localize it to UTC
utc_date = pytz.utc.localize(naive_date)
# Convert to the specified timezone
tz = pytz.timezone(timezone)
local_date = utc_date.astimezone(tz)
return {
"day_of_week": local_date.strftime("%A"),
"month_name": local_date.strftime("%B"),
"month_day_number": p_ordinal(local_date.day),
"year_number": local_date.strftime("%Y"),
"time": local_date.strftime("%I:%M %p %Z")
}
except (ValueError, pytz.exceptions.UnknownTimeZoneError):
return {"error": "Invalid date or timezone format."}
@app.post("/format-date")
async def date_format_handler(request: Request):
body = request.json
if 'date' not in body or 'timezone' not in body:
return json({"error": "Date and timezone must be provided in JSON"}, status=400)
formatted_date = format_date(body['date'], body['timezone'])
return json(formatted_date)
# ... rest of your routes ...
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment