Convert DD (decimal degrees) to DMS (degrees minut

2019-01-14 17:13发布

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

8条回答
爷、活的狠高调
2楼-- · 2019-01-14 17:23

Use fmod and rounding to get the degrees and fraction separated. Multiply the fraction by 60 and repeat to get minutes and a remainder. Then multiply that last part by 60 again to get the number of seconds.

查看更多
干净又极端
3楼-- · 2019-01-14 17:24

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
>>> 
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-14 17:25

This is exactly what divmod was invented for:

>>> def decdeg2dms(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)
查看更多
我只想做你的唯一
5楼-- · 2019-01-14 17:27

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)
查看更多
乱世女痞
6楼-- · 2019-01-14 17:38

The sign has better be returned separately, so that it can be used to choose from ('N', 'S') or ('E', 'W'), for example.

import math

def dd_to_dms(degs):
    neg = degs < 0
    degs = (-1) ** neg * degs
    degs, d_int = math.modf(degs)
    mins, m_int = math.modf(60 * degs)
    secs        =           60 * mins
    return neg, d_int, m_int, secs
查看更多
放我归山
7楼-- · 2019-01-14 17:39

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)
查看更多
登录 后发表回答