How can I parse this correctly?

Ben Finney ben+python at benfinney.id.au
Sun Apr 6 00:21:27 EDT 2014


Anthony Papillion <papillion at gmail.com> writes:

> for row in r:
>     print row['YEAR']
>
> This works fine. But, I am needing to do date addition/subtraction
> using datetime and so I need these dates as integers.

I assume you mean you will be creating ‘datetime.date’ objects. What
will you set as the month and day?

Alternatively, if you just want to do integer arithmetic on the year,
you don't need the ‘datetime’ module at all.

> When I try to cast them like this:

Python doesn't have “cast”; instead, you request the creation of a new
object by calling the type.

> print int(row['YEAR'])

What do you expect this to return when ‘row['YEAR']’ is ‘""’ (empty
string)?

> I am told by the interpreter:
>
> Traceback (most recent call last):
>   File "analyze.py", line 14, in <module>
>     print int(row['MONTH'])
> ValueError: invalid literal for int() with base 10: ''
>
> What am I doing wrong?

You've ignored the condition where your ‘row['YEAR']’ is the empty
string. Python doesn't have an unambiguous integer represented by the
empty string, so it refuses to guess.

You'll need to handle that specially, and decide what value you want
when that's the case.

-- 
 \        “A free press is one where it's okay to state the conclusion |
  `\                      you're led to by the evidence.” —Bill Moyers |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list