Skip to content

Instantly share code, notes, and snippets.

@jeteon
Forked from tomwhipple/dms2dec.py
Last active June 4, 2021 17:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jeteon/89c41e4081d87b798d8006b16a52c695 to your computer and use it in GitHub Desktop.
Save jeteon/89c41e4081d87b798d8006b16a52c695 to your computer and use it in GitHub Desktop.
Convert coordinates in DMS notation to decimal in Python.
#!/env/python
# coding=utf8
"""
Converting Degrees, Minutes, Seconds formatted coordinate strings to decimal.
Formula:
DEC = (DEG + (MIN * 1/60) + (SEC * 1/60 * 1/60))
Assumes S/W are negative.
"""
import re
def dms2dec(dms_str):
"""Return decimal representation of DMS
>>> dms2dec(utf8(48°53'10.18"N))
48.8866111111F
>>> dms2dec(utf8(2°20'35.09"E))
2.34330555556F
>>> dms2dec(utf8(48°53'10.18"S))
-48.8866111111F
>>> dms2dec(utf8(2°20'35.09"W))
-2.34330555556F
"""
dms_str = re.sub(r'\s', '', dms_str)
sign = -1 if re.search('[swSW]', dms_str) else 1
numbers = filter(len, re.split('\D+', dms_str, maxsplit=4))
degree = numbers[0]
minute = numbers[1] if len(numbers) >= 2 else '0'
second = numbers[2] if len(numbers) >= 3 else '0'
frac_seconds = numbers[3] if len(numbers) >= 4 else '0'
second += "." + frac_seconds
return sign * (int(degree) + float(minute) / 60 + float(second) / 3600)
@ytzhang0925
Copy link

In Python 3, filter() returns a iterable filter object rather than a list.
numbers should be converted to list using list(): numbers = list(numbers) before subscription.
Otherwise, call method next() to get items one by one from iterable numbers.

@chrisjsimpson
Copy link

Updated to python 3 https://gist.github.com/chrisjsimpson/076a82b51e8540a117e8aa5e793d06ec

@ytzhang0925 there must be a better way" do please share if you wish 👍

@FrankThonig
Copy link

very nice. thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment