如何在特定字符之前测量字符串的长度



我正在调用一个API,它为我提供我所请求的特定城市的日出时间。

问题是,当日出在上午10点之前时,我会得到它的格式,例如'9:10 am'。这把我的代码搞砸了,我需要'09:10 am'格式的代码。我使用UTC时间取决于地点,这就是为什么它可以给我上午或下午的时间。

有没有办法知道特定字符之前的字符串长度,在这种情况下是':'

示例字符串

{"results":{"sunrise":"9:28:40 PM","sunset":"10:16:12 AM","solar_noon":"3:52:26 AM","day_length":"12:47:32","civil_twilight_begin":"9:05:59 PM","civil_twilight_end":"10:38:53 AM","nautical_twilight_begin":"8:39:14 PM","nautical_twilight_end":"11:05:38 AM","astronomical_twilight_begin":"8:12:02 PM","astronomical_twilight_end":"11:32:50 AM"},"status":"OK"}

您可以使用以下内容:

import json
file = open('time.json', 'r')
data = json.loads(file.read())
file.close()
sunrise = data['results']['sunrise']
### This is the part that measures the length before ':'
length = sunrise.find(':')
print(length)

最新更新