Wednesday, November 30, 2011

Convert Decimal Degree to Degrees Minutes Seconds Using Python

Here is a function that will convert decimal degree values to degrees, minutes, and seconds.  It's nice to show DMS notation as labels for points at times, so here is a script I made to do this:

def decimalDegrees2DMS(value,type):
        Converts a Decimal Degree Value into
        Degrees Minute Seconds Notation.
        Pass value as double
        type = {Latitude or Longitude} as string
        returns a string as D:M:S:Direction
        created by: 
    degrees = int(value)
    submin = abs( (value - int(value) ) * 60)
    minutes = int(submin)
    subseconds = abs((submin-int(submin)) * 60)
    direction = ""
    if type == "Longitude":
        if degrees < 0:
            direction = "W"
        elif degrees > 0:
            direction = "E"
            direction = ""
    elif type == "Latitude":
        if degrees < 0:
            direction = "S"
        elif degrees > 0:
            direction = "N"
            direction = "" 
    notation = str(degrees) + ":" + str(minutes) + ":" +\
               str(subseconds)[0:5] + "" + direction
    return notation

It's a very simple function, but very useful.  Feel free to use it, but give my blog some love and cite me.


Gus said...

Thank you so much for posting this.

You saved me so much time.

Anonymous said...

Yes I agree. I haven't tried it out yet but I will soon and a huge time saver and I have just looked at it. Thanks for the post!

Sarah Lou said...

Does ArcView3x only recognize decimal degrees? I am trying to create a shapefile and my data won't show up in the view. Thank you!

Anonymous said...

Should this be used in the field calculator or a script in the toolbox? If toolbox then what parameters should be set? I'm using 10. Thanks :)

Andrew said...

It's just a function that can go into any python file.

Inputs should be float for the first value, and a string for the second.

Anonymous said...

This code is not going to return the correct direction for values that are in the range (-1.0, 1.0) because you make the decision based on the degrees, which has already been truncated. You need to compute the direction from the original value before truncating it.