Skip to content Skip to sidebar Skip to footer

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?

Solution 1:

This is exactly what divmod was invented for:

>>>defdecdeg2dms(dd):...  mnt,sec = divmod(dd*3600,60)...  deg,mnt = divmod(mnt,60)...return deg,mnt,sec>>>dd = 45 + 30.0/60 + 1.0/3600>>>print dd
45.5002777778
>>>decdeg2dms(dd)
(45.0, 30.0, 1.0)

Solution 2:

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)

Solution 3:

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)

Solution 4:

Just a couple of * 60 multiplications and a couple of int truncations, i.e.:

>>>decdegrees = 31.125>>>degrees = int(decdegrees)>>>temp = 60 * (decdegrees - degrees)>>>minutes = int(temp)>>>seconds = 60 * (temp - minutes)>>>print degrees, minutes, seconds
31 7 30.0
>>>

Solution 5:

This is my Python code:

defDecimaltoDMS(Decimal):
    d = int(Decimal)
    m = int((Decimal - d) * 60)
    s = (Decimal - d - m/60) * 3600.00
    z= round(s, 2)
    if d >= 0:
        print ("N ", abs(d), "º ", abs(m), "' ", abs(z), '" ')
    else:
        print ("S ", abs(d), "º ", abs(m), "' ", abs(z), '" ')

Post a Comment for "Convert Dd (decimal Degrees) To Dms (degrees Minutes Seconds) In Python?"