-
-
Save dustinmichels/0f2151bf40b2266ffb05941505d2ab72 to your computer and use it in GitHub Desktop.
Convert coordinates in DMS notation to decimal in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| def dms2dec(dms_str): | |
| """ | |
| Return decimal representation of DMS. | |
| - Formula: DEC = (DEG + (MIN * 1/60) + (SEC * 1/60 * 1/60)) | |
| - Assumes S/W are negative | |
| - Based on: https://gist.github.com/chrisjsimpson/076a82b51e8540a117e8aa5e793d06ec | |
| Examples: | |
| >>> dms2dec("71°6′3.0″W") | |
| -71.10083333333333 | |
| >>> dms2dec("40 degrees, 42 minutes, 51 seconds N") | |
| 40.71416666666666 | |
| """ | |
| # strip whitespace | |
| dms_str = dms_str.strip() | |
| # extract sign based on final character | |
| sign = -1 if dms_str[-1] in list("swSW") else 1 | |
| # split on non-digit values | |
| # Eg, '71°6′3.0″W' => ['71', '6', '3', '0', ''] | |
| parts = re.split(r"\D+", dms_str, maxsplit=4) | |
| # filter out empty str values | |
| numbers = [x for x in parts if len(x) > 0] | |
| # sort of which number is which | |
| 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 = f"{second}.{frac_seconds}" | |
| # apply formula | |
| return sign * (int(degree) + float(minute) / 60 + float(second) / 3600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment