调用Google Maps API获取路线遇HTTP 400错误(Python Googlemaps库)
departure_time in Google Maps Python Client Hey there! That HTTP 400 error is definitely tied to your departure_time parameter—let's break down why and how to fix it.
The Google Maps Directions API doesn't accept human-readable date strings like "2018-04-05 09:00:00" for departure_time. Instead, it expects one of two valid formats:
- A UNIX timestamp (integer representing seconds since January 1, 1970 UTC)
- The string
"now"for real-time departure calculations
Solution 1: Convert your date string to a UNIX timestamp
Use Python's built-in datetime and time modules to convert your desired departure time into the correct format. Here's a working example:
from datetime import datetime import time # Parse your date string into a datetime object departure_datetime = datetime.strptime("2018-04-05 09:00:00", "%Y-%m-%d %H:%M:%S") # Convert to UNIX timestamp (seconds since epoch) departure_timestamp = int(time.mktime(departure_datetime.timetuple())) # Updated API call with valid departure_time directions_result = gmaps.directions( IN, OUT, mode="driving", departure_time=departure_timestamp, traffic_model='pessimistic', alternatives=False, language="ja" )
Solution 2: Handle Time Zones (Critical for Accuracy)
Since you're using language="ja", your departure time is likely in Japan Standard Time (JST). To avoid UTC conversion errors, explicitly handle time zones with the pytz library:
First, install pytz if you haven't already:
pip install pytz
Then adjust your code to account for the time zone:
from datetime import datetime import pytz # Define the Japan time zone jst_timezone = pytz.timezone('Asia/Tokyo') # Parse the date string and attach the correct time zone departure_datetime = jst_timezone.localize(datetime.strptime("2018-04-05 09:00:00", "%Y-%m-%d %H:%M:%S")) # Convert to UTC-based UNIX timestamp departure_timestamp = int(departure_datetime.timestamp()) # Final API call with time zone-aware timestamp directions_result = gmaps.directions( IN, OUT, mode="driving", departure_time=departure_timestamp, traffic_model='pessimistic', alternatives=False, language="ja" )
Why This Works
HTTP 400 errors for the Google Maps API almost always indicate a malformed request parameter. By switching to the UNIX timestamp format the API explicitly expects, you're providing the exact data it needs to calculate route times with traffic predictions.
内容的提问来源于stack exchange,提问作者user9191983

