Learning Scientific Programming with Python (2nd edition)
Q2.X.1: Converting decimal degrees to deg, min, sec
Question Q2.X.1
Write a program to convert an longitude or latitude expressed as a signed quantity in degrees (possibly with a fractional component expressed in decimal notation) to one expressed in degrees, minutes and seconds (the first two as integers and the last as a floating point number). Input latitudes may be $-90 - +90$ and longitudes $-180 - +180$.
In addition to the numerical values of degrees, minutes and seconds, also output a string in the form deg° min′ sec″ X
where X
is N
, S
, E
, or W
as appropriate. For example,
In [x]: deg_to_dms(38.889469)
Out[x]: (38, 53, 22.088400000007823)
In [x]: deg_to_dms(38.889469, pretty_print='latitude')
Out[x]: '38° 53′ 22.0884″ N'
In [x]: deg_to_dms(-77.035258)
Out[x]: (-77, 2, 6.928799999994226)
In [x]: deg_to_dms(-77.035258, pretty_print='longitude')
Out[x]: '77° 2′ 6.9288″ W'