Code in python the equivalent of the VB Format function

6146
26
01-14-2011 03:32 AM
JoseSanchez
Occasional Contributor III
Hi all

I am using ArcGIs 9.3 and Model Bulder. I was able to code a calculate field in VB that formats a field as follows Format("08.00.00") and converts it to "08:00:00 AM"

How can I do the same thing in Python (phyton 3 or python)?

Please advise!
Tags (2)
0 Kudos
26 Replies
ChrisMathers
Occasional Contributor III
This will work to edit the string directly. Or you can use the time module and do all sorts of things to it.
 
astring="08.00.00".replace('.',':')
if int(astring.split(':')[0]) < 12:
    astring+=' AM'
else:
    astring+=' PM'
0 Kudos
MustafaELHalwagy
New Contributor
i have the same problem,how can i write expression by Python in Raster Calculator,i have many problem with applied expression (syntax) by Python, there were many different in VB and Python, so can any one help me how can i do it in Python....please
0 Kudos
ChrisSnyder
Regular Contributor III
Sounds like you need to learn Python...

Do you have any specific examples of VBA code you need to convert to Python?
0 Kudos
MustafaELHalwagy
New Contributor
OK, thank you very much, for example,

EXPAND([Streams_rr2m],10,LIST,1.2)

INT([Ran_Ras] * 10) + 1

[Angles] * 57.296

so if you have any information about typing expressions by python plz help me, precisely (Raster Calculator operators and functions)
thank you very much again for interesting and following my post
0 Kudos
ChrisSnyder
Regular Contributor III
Are you using ArcGIS v10 or v9.3? In v10 there is a new raster calculator syntax that I am not up and running with yet. However, even in v10 you can still use the good old MapAlgebra syntax via Python. For example:

#EXPAND([Streams_rr2m],10,LIST,1.2)
import arcgisscripting
gp = arcgisscripting.create(9.3)
gp.CheckOutExtension("Spatial")
inputGrd = r"C:\temp\input"
somaExp = "expand(" + inputGrd + ", 10, 'LIST', 1.2)"
outputGrd = r"C:\temp\output"
gp.SingleOutputMapAlgebra_sa(somaExp, outputGrd, "")

#INT([Ran_Ras] * 10) + 1
import arcgisscripting
gp = arcgisscripting.create(9.3)
gp.CheckOutExtension("Spatial")
inputGrd = r"C:\temp\input"
somaExp = "int(" + inputGrd + " * 10 + 1)"
outputGrd = r"C:\temp\output"
gp.SingleOutputMapAlgebra_sa(somaExp, outputGrd, "")

#[Angles] * 57.296
import arcgisscripting
gp = arcgisscripting.create(9.3)
gp.CheckOutExtension("Spatial")
inputGrd = r"C:\temp\input"
somaExp = inputGrd + " * 57.296"
outputGrd = r"C:\temp\output"
gp.SingleOutputMapAlgebra_sa(somaExp, outputGrd, "")
0 Kudos
MustafaELHalwagy
New Contributor
I have ArcGis 10,
i have tried to apply this syntax ("expand(" + inputGrd + ", 10, 'LIST', 1.2)"), but i have the same error.

                    


                                    

thank you
0 Kudos
NiklasNorrthon
Occasional Contributor III
Here is a python crash course for the field calculator (assuming ArcGIS 10):

First of all python is just as easy as VB (if not easier). It's just a different language, so the syntax is not identical to VB. That means that you can't write VB in python, just as you can't write C++, Perl or C# in python, so yes you need to learn a little python to write python.

Second: The field calculator is actually extending the python language with the notation of "fields names" just as it did with VB. In VB field calculator you quote field names with sqaure brackets: [field_name]. In python you do the same, but with exclamation marks instead: !field_name!. That is because square brackets already have a different meaning in python.

Third: String formatting in python is much more powerful than i VB, and also very different from VB. To format a string in python one creates a "format string" and then use the format operator:
"This is a %s with the integer %d and the float %.4f" % ('format string', 42, 3.14159265)

Fourth: To pick substring from a string, one use index and slicing:
"mississippi"[0] # -> "m"
"mississippi"[:4] # -> "miss" # End at the 4th character
"mississippi"[-4:] # ->"ippi" # Start is 4th from the right
"mississippi"[::-1] # -> "ippississim" # Stepping backwards
"mississippi"[1::3] # -> "iiii" # Start at 1, and step 3

So for some field calculator examples:
To copy the contents from one field to another, just quote the source field name in exclamation marks:
!source_field!

To copy and format floating point numbers to a text field, use a format string:
"%.3f" % !source_float_field!

To fill a column with the time of day, formatted in 12 hour format:
First check the "Show codeblock" checkbox, then in the Pre-Logic Script Code box enter the following:
import datetime
t = datetime.datetime.now()

Then in the calc field code box below enter the following:
t.strftime('%I:%M:%S %p) # See python help for strftime for details


Given a float field with POSIX timestamps (seconds since epoch). To convert that to a date and time string in ISO format (2010-01-15 06:43:12):
in the pre-logic box enter:
import datetime

and in the calc window enter:
datetime.datetime.fromtimestamp(!time_stamp_field!).strftime('%Y-%m-%d %H:%M:%S')


Try these examples out and then come back with more specific questions about the Calculate Field functionallity. Also keep in mind that some people here (me included), might not be fluent in VB, so examples of what you expect specific VB code snippets to do is helpful.
0 Kudos
MustafaELHalwagy
New Contributor
Here is a python crash course for the field calculator (assuming ArcGIS 10):

First of all python is just as easy as VB (if not easier). It's just a different language, so the syntax is not identical to VB. That means that you can't write VB in python, just as you can't write C++, Perl or C# in python, so yes you need to learn a little python to write python.

Second: The field calculator is actually extending the python language with the notation of "fields names" just as it did with VB. In VB field calculator you quote field names with sqaure brackets: [field_name]. In python you do the same, but with exclamation marks instead: !field_name!. That is because square brackets already have a different meaning in python.

Third: String formatting in python is much more powerful than i VB, and also very different from VB. To format a string in python one creates a "format string" and then use the format operator:
"This is a %s with the integer %d and the float %.4f" % ('format string', 42, 3.14159265)

Fourth: To pick substring from a string, one use index and slicing:
"mississippi"[0] # -> "m"
"mississippi"[:4] # -> "miss" # End at the 4th character
"mississippi"[-4:] # ->"ippi" # Start is 4th from the right
"mississippi"[::-1] # -> "ippississim" # Stepping backwards
"mississippi"[1::3] # -> "iiii" # Start at 1, and step 3

So for some field calculator examples:
To copy the contents from one field to another, just quote the source field name in exclamation marks:
!source_field!

To copy and format floating point numbers to a text field, use a format string:
"%.3f" % !source_float_field!

To fill a column with the time of day, formatted in 12 hour format:
First check the "Show codeblock" checkbox, then in the Pre-Logic Script Code box enter the following:
import datetime
t = datetime.datetime.now()

Then in the calc field code box below enter the following:
t.strftime('%I:%M:%S %p) # See python help for strftime for details


Given a float field with POSIX timestamps (seconds since epoch). To convert that to a date and time string in ISO format (2010-01-15 06:43:12):
in the pre-logic box enter:
import datetime

and in the calc window enter:
datetime.datetime.fromtimestamp(!time_stamp_field!).strftime('%Y-%m-%d %H:%M:%S')


Try these examples out and then come back with more specific questions about the Calculate Field functionallity. Also keep in mind that some people here (me included), might not be fluent in VB, so examples of what you expect specific VB code snippets to do is helpful.


Thank u very much niklas.norrthon, i had tried to write the syntax again by following ur post,put the same problem had appeared again, so if you want to try this by urself, and what can i do with this expression
for example 
Streams_rr2m],10,LIST,1.2)(vb)
thank you very much again
0 Kudos
NiklasNorrthon
Occasional Contributor III
I don't know what your VB function is supposed to do. If you can give an example of unformatted data, and how you want it formatted I might be able to help you.
0 Kudos