Reputation: 62624
Assuming I have the following:
latitude = "20-55-70.010N"
longitude = "32-11-50.000W"
What is the easiest way to convert to decimal form? Is there some library?
Would converting from this seconds form be simpler?
"149520.220N"
"431182.897W"
Upvotes: 7
Views: 18896
Reputation: 386
To handle "N", "S", "W" and "E", one would tweak @wwii's solution:
def convert(tude):
multiplier = 1 if tude[-1] in ['N', 'E'] else -1
return multiplier * sum(float(x) / 60 ** n for n, x in enumerate(tude[:-1].split('-')))
then:
print('20-55-70.010N: ' + convert('20-55-70.010N'))
print('32-11-50.000W: ' + convert('32-11-50.000W'))
results in:
20-55-70.010N: 20.9361138889
32-11-50.000W: -32.1972222222
Upvotes: 11
Reputation: 23753
This should do the trick
latitude = "20-55-70.010N"
longitude = "32-11-50.000W"
##assuming N latitude and W longitude
latitude = sum(float(x) / 60 ** n for n, x in enumerate(latitude[:-1].split('-'))) * (1 if 'N' in latitude[-1] else -1)
longitude = sum(float(x) / 60 ** n for n, x in enumerate(longitude[:-1].split('-'))) * (1 if 'E' in longitude[-1] else -1)
That's getting a bit long for my tastes, maybe keep it simple:
latitude = "20-55-70.010N"
N = 'N' in latitude
d, m, s = map(float, latitude[:-1].split('-'))
latitude = (d + m / 60. + s / 3600.) * (1 if N else -1)
longitude = "32-11-50.000W"
W = 'W' in longitude
d, m, s = map(float, longitude[:-1].split('-'))
longitude = (d + m / 60. + s / 3600.) * (-1 if W else 1)
Upvotes: 4