Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69739

Re: How can I parse this correctly?

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: How can I parse this correctly?
Date 2014-04-06 14:21 +1000
References <CAJUMiQsoNbNzDgUOkaQxFLGptTqKriD7DcXSeFwwu_-v4TKJKQ@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.8934.1396758100.18130.python-list@python.org> (permalink)

Show all headers | View raw


Anthony Papillion <papillion@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: How can I parse this correctly? Ben Finney <ben+python@benfinney.id.au> - 2014-04-06 14:21 +1000

csiph-web