如何在Python中将十进制度数转换为度分秒?是否已经有现成的公式可用?
如何在Python中将十进制度数转换为度分秒?是否已经有现成的公式可用?
这正是 divmod
的用途所在:
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))
输出:
(45.0, 30.0, 1.0)
(-122.0, -26.0, -31.199999999953434)
(-122, -26, -31.12)
吗?我认为 -123 + 33/60 + 28.8/3600
实际上等于 -122.442
。 - PaulMcG这是我基于Paul McGuire的更新版本。这个版本应该正确处理负数。
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)
is_positive
为 False,则还需要对 minutes
和 seconds
取反。 - PaulMcGdef 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)
只需要进行几个* 60
的乘法和几次int
的截断,即可实现:
>>> 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
>>>
这是我的Python代码:
def DecimaltoDMS(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), '" ')
Decimal
用作变量名称可能会与decimal.Decimal
冲突,并不是一个好主意。 - musiphil def deg_to_dms(deg, type='lat'):
decimals, number = math.modf(deg)
d = int(number)
m = int(decimals * 60)
s = (deg - d - m / 60) * 3600.00
compass = {
'lat': ('N','S'),
'lon': ('E','W')
}
compass_str = compass[type][0 if d >= 0 else 1]
return '{}º{}\'{:.2f}"{}'.format(abs(d), abs(m), abs(s), compass_str)
这是我略微不同的方法,对于正负十进制度数在我的惠普Prime上与原方法相同...
def dms(deg):
f,d = math.modf(deg)
s,m = math.modf(abs(f) * 60)
return (d,m,s * 60)
最好将该符号分开返回,这样就可以用于选择('N', 'S')
或('E', 'W')
等。
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
现在我们可以使用LatLon库了...
https://pypi.org/project/LatLon/
>> palmyra = LatLon(Latitude(5.8833), Longitude(-162.0833)) # Location of Palmyra Atoll in decimal degrees
>> palmyra = LatLon(5.8833, -162.0833) # Same thing but simpler!
>> palmyra = LatLon(Latitude(degree = 5, minute = 52, second = 59.88),
Longitude(degree = -162, minute = -4.998) # or more complicated!
>> print palmyra.to_string('d% %m% %S% %H') # Print coordinates to degree minute second
('5 52 59.88 N', '162 4 59.88 W')`
import latlon
导入模块。请注意,您需要使用以下语法 from latlon import LatLon
才能使这些示例正常工作。请注意大小写。 - user6743474fmod
和四舍五入来分离度数和小数部分。将小数部分乘以60并重复操作,得到分钟和余数。然后再将最后一部分乘以60,得到秒数。math.modf
。 - musiphil