DMS conversion method not accepting input without seconds component

24 Views Asked by At

I have a method in my Python code that converts latitude and longitude to Degree-Minute-Second (DMS) format. However, I noticed that the method only accepts input in the format 44°05′00″N 120°34′00″W, where the seconds component is explicitly specified. When I try to input latitude and longitude without the seconds component, like 44°05′N 120°34′W, the method raises an error.

def convert_dms_to_lat_long(self, dms):
        # Convert DMS format to latitude and longitude
        lat_deg, lat_min, lat_sec, lat_dir, long_deg, long_min, long_sec, long_dir = re.findall(r'\d+|[NSEW]', dms)
        lat = int(lat_deg) + float(lat_min)/60 + float(lat_sec)/3600
        long = -(int(long_deg) + float(long_min)/60 + float(long_sec)/3600) if long_dir in ['S', 'W'] else int(long_deg) + float(long_min)/60 + float(long_sec)/3600
        return round(lat, 5), round(long, 5)

Is there a way to modify this method so that it accepts input without the seconds component in the DMS format? For example: for open test: gc_dakota: GeoCoordinates(dms=44°05′N 120°34′W), I want the output to be Coordinates of dakota to be: 44°05′N 120°34′W

1

There are 1 best solutions below

0
Andrej Kesely On

Try:

import re


def convert_dms_to_lat_long(dms):
    # Convert DMS format to latitude and longitude
    lat_deg, lat_min, lat_sec, lat_dir, long_deg, long_min, long_sec, long_dir = (
        re.match(
            r"(\d+)°(\d+)′(?:(\d+)″)?([NSEW]) (\d+)°(\d+)′(?:(\d+)″)?([NSEW])", dms
        ).groups()
    )
    lat_sec = 0 if lat_sec is None else lat_sec
    long_sec = 0 if long_sec is None else long_sec

    lat = int(lat_deg) + float(lat_min) / 60 + float(lat_sec) / 3600
    long = (
        -(int(long_deg) + float(long_min) / 60 + float(long_sec) / 3600)
        if long_dir in ["S", "W"]
        else int(long_deg) + float(long_min) / 60 + float(long_sec) / 3600
    )
    return round(lat, 5), round(long, 5)


print(convert_dms_to_lat_long("44°05′00″N 120°34′00″W"))
print(convert_dms_to_lat_long("44°05′N 120°34′00″W"))
print(convert_dms_to_lat_long("44°05′00″N 120°34′W"))
print(convert_dms_to_lat_long("44°05′N 120°34′W"))

Prints:

(44.08333, -120.56667)
(44.08333, -120.56667)
(44.08333, -120.56667)
(44.08333, -120.56667)