Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DD (decimal degrees) to DMS (degrees minutes seconds) in Python?

How do you convert Decimal Degrees to Degrees Minutes Seconds In Python? Is there a Formula already written?

like image 829
David Avatar asked Apr 05 '10 16:04

David


People also ask

What is DD vs DMS coordinates?

The key for knowing the difference is watching for the presence of a decimal in the coordinate string. If there is no decimal, it is DMS. If the decimal imme- diately follows the minutes coordinate (61° 34.25' or 61 34.25) then it's DM. If the decimal immediately follows the degrees coordinate (61.5708) then it's DD.


3 Answers

This is exactly what divmod was invented for:

def decdeg2dms(dd):
    mult = -1 if dd < 0 else 1
    mnt,sec = divmod(abs(dd)*3600, 60)
    deg,mnt = divmod(mnt, 60)
    return mult*deg, mult*mnt, mult*sec

dd = 45 + 30/60 + 1/3600
print(decdeg2dms(dd))

# negative value returns all negative elements
print(decdeg2dms(-122.442))

Prints:

(45.0, 30.0, 1.0)
(-122.0, -26.0, -31.199999999953434)
like image 185
PaulMcG Avatar answered Oct 27 '22 17:10

PaulMcG


Here is my updated version based upon Paul McGuire's. This one should handle negatives correctly.

def decdeg2dms(dd):
   is_positive = dd >= 0
   dd = abs(dd)
   minutes,seconds = divmod(dd*3600,60)
   degrees,minutes = divmod(minutes,60)
   degrees = degrees if is_positive else -degrees
   return (degrees,minutes,seconds)
like image 22
Erik L Avatar answered Oct 27 '22 18:10

Erik L


If you want to handle negatives properly, the first non-zero measure is set negative. It is counter to common practice to specify all of degrees, minutes and seconds as negative (Wikipedia shows 40° 26.7717, -79° 56.93172 as a valid example of degrees-minutes notation, in which degrees are negative and minutes have no sign), and setting degrees as negative does not have any effect if the degrees portion is 0. Here is a function that adequately handles this, based on Paul McGuire's and baens' functions:

def decdeg2dms(dd):
    negative = dd < 0
    dd = abs(dd)
    minutes,seconds = divmod(dd*3600,60)
    degrees,minutes = divmod(minutes,60)
    if negative:
        if degrees > 0:
            degrees = -degrees
        elif minutes > 0:
            minutes = -minutes
        else:
            seconds = -seconds
    return (degrees,minutes,seconds)
like image 36
iamed2 Avatar answered Oct 27 '22 17:10

iamed2