1+ import json
2+ import boto3
3+ from datetime import datetime
4+ import pytz
5+ import re
6+
7+ def lambda_handler (event , context ):
8+ # Parse input from Bedrock agent
9+ input_text = event ['inputText' ]
10+
11+ # Extract timezone from user input (e.g., "What time is it in Europe/London?")
12+ timezone = extract_timezone (input_text )
13+
14+ if not timezone :
15+ # If no timezone specified, use UTC or prompt user
16+ return {
17+ 'statusCode' : 200 ,
18+ 'response' : {
19+ 'message' : "I can tell you the current time. Please specify a timezone (e.g., 'What time is it in New York?') or I can use UTC."
20+ }
21+ }
22+
23+ try :
24+ # Get current time in specified timezone
25+ current_time = get_current_time (timezone )
26+ response_message = f"The current time in { timezone } is { current_time } ."
27+ except pytz .UnknownTimeZoneError :
28+ response_message = f"Sorry, I don't recognize the timezone '{ timezone } '. Please try another major city or timezone."
29+
30+ return {
31+ 'statusCode' : 200 ,
32+ 'response' : {
33+ 'message' : response_message
34+ }
35+ }
36+
37+ def extract_timezone (text ):
38+ # Look for timezone patterns in the user input
39+ patterns = [
40+ r'in\s+(?:the\s+)?(?:timezone\s+)?([A-Za-z\/_]+)' , # "in Europe/London"
41+ r'in\s+([A-Za-z\s]+)$' , # "in New York"
42+ r'for\s+([A-Za-z\s]+)$' # "time for Tokyo"
43+ ]
44+
45+ for pattern in patterns :
46+ match = re .search (pattern , text , re .IGNORECASE )
47+ if match :
48+ timezone_str = match .group (1 ).strip ()
49+ return convert_city_to_tz (timezone_str )
50+
51+ return None
52+
53+ def convert_city_to_tz (city_name ):
54+ # Map common city names to timezones
55+ city_to_tz = {
56+ 'new york' : 'America/New_York' ,
57+ 'london' : 'Europe/London' ,
58+ 'tokyo' : 'Asia/Tokyo' ,
59+ 'paris' : 'Europe/Paris' ,
60+ 'los angeles' : 'America/Los_Angeles' ,
61+ 'chicago' : 'America/Chicago' ,
62+ 'sydney' : 'Australia/Sydney' ,
63+ 'berlin' : 'Europe/Berlin'
64+ }
65+
66+ lower_city = city_name .lower ()
67+ return city_to_tz .get (lower_city , city_name ) # Return original if not in map
68+
69+ def get_current_time (timezone ):
70+ # Get current time in specified timezone
71+ tz = pytz .timezone (timezone )
72+ now = datetime .now (tz )
73+ return now .strftime ('%Y-%m-%d %H:%M:%S %Z' )
0 commit comments