如何通过Google Places API获取商家每日营业时间?
获取商家一周营业时间的解决方案
你当前使用的places方法(对应Google Places文本搜索API)仅返回简化的open_now状态,无法直接获取一周完整营业时间。要拿到这些信息,必须通过Place Details API,也就是googlemaps库中的place方法,利用文本搜索得到的place_id发起二次请求。
完整实现示例
import googlemaps # 初始化客户端 gmaps = googlemaps.Client(key='你的API密钥') # 1. 文本搜索获取商家基本信息及place_id charlestonBars = ["A.C.'s Bar & Grill"] charleston = (32.7767, -79.9310) # 查尔斯顿地理坐标 search_response = gmaps.places(query=charlestonBars[0], location=charleston) if search_response['results']: # 提取目标商家的place_id target_place_id = search_response['results'][0]['place_id'] # 2. 调用Place Details API获取完整营业信息 details_response = gmaps.place(place_id=target_place_id) opening_hours = details_response['result'].get('opening_hours', {}) # 解析并输出营业时间 if 'weekday_text' in opening_hours: print("一周营业时间:") for day_schedule in opening_hours['weekday_text']: print(day_schedule) elif 'periods' in opening_hours: print("结构化营业时间:") # 0=周日,1=周一,以此类推到6=周六 weekday_map = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"] for period in opening_hours['periods']: day_idx = period['open']['day'] start = period['open']['time'] end = period['close']['time'] if 'close' in period else "全天营业" print(f"{weekday_map[day_idx]}: {start[:2]}:{start[2:]} - {end[:2]}:{end[2:]}") else: print("该商家未公开完整营业时间") else: print("未找到匹配的商家")
注意事项
- 确保你的API密钥已启用Place Details API,并拥有对应访问权限
- 部分商家可能未公开完整营业时间,此时返回的
opening_hours可能仅包含open_now或为空 - Place Details API有独立的调用配额和计费规则,需注意使用成本
内容的提问来源于stack exchange,提问作者Justin Priede
相关产品推荐
相关产品推荐

