-1

I'm calling an API which gives me the sunrise time of specific cities I request.

The issue is that when the sunrise is before 10 am I get it in the format, for example, '9:10 am'. This messes up my code and I need it in the format '09:10 am'. I'm using UTC time depending on the location which is why it can give me time in am or pm.

Is there a way to know the length of a string before a specific character, in this case ':'?

Example string

{"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"}
Reti43
  • 9,656
  • 3
  • 28
  • 44
pentaaax
  • 19
  • 1
  • 7
  • 1
    What code are you using to parse this string? An easier solution might be to use `datetime.datetime.strptime()`. – Samwise May 12 '21 at 21:45
  • Here is an example https://api.sunrise-sunset.org/json?lat=14.5958&lng=120.9772&date=today – pentaaax May 12 '21 at 22:25

1 Answers1

0

You could use the following:

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)
AcidResin
  • 134
  • 2
  • 12