Last night I was reading through Hello World!, an introductory programming book loaned to me by a coworker, and decided to give Python a crack. Here’s my first attempt. Just paste it into a text editor and save as ‘lat2dms.py’. Then run it in IDLE GUI (free download) with F5. If you type lat2dms(###) in IDLE it will convert the decimal degree value ‘###’ to degree-minute-second format (four outputs, including N/S to indicate direction). I originally wrote it to output a concatenated string of those values but couldn’t figure out how to include the degree, minute, or second symbols (eg ‘ and ”). My ultimate goal is to use this as a building block for a script that will import a CSV file with geodata in one format and output a new CSV file with the same data in a different format, suitable to be used with Excel or any compatible geographic information system. I’m about halfway through the loops chapter, so hopefully that will come in handy. This has been a fun exercise and I hope I can continue learning on the side.
#this is a program to convert a decimal latitude value into degrees minutes seconds format #by Will Townes 25 AUG. 2009 #https://willtownes.wordpress.com def lat2dms(ilat): #this conditional defines whether the lat. is north or south if ilat>=0: direction = 'North' else: direction = 'South' ilat = abs(ilat) #here we parse the initial, decimal value into degrees minutes and seconds. degrees = int(ilat) rawminutes = 60*(ilat-degrees) minutes = int(rawminutes) seconds = int(60*(rawminutes-minutes)) if ilat > 90: print "ERROR- invalid latitude value. Please enter a value between -90 and 90." else: print "(degrees, minutes, seconds, direction)" return degrees, minutes, seconds, direction