How can I parse this correctly?

Anthony Papillion papillion at gmail.com
Sun Apr 6 02:49:52 EDT 2014


On Apr 5, 2014, at 23:21, Ben Finney <ben+python at benfinney.id.au> wrote:

> 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. Wh 
> at
> will you set as the month and day?

Right, I did mean datetime.date. As form month and day, I also have a  
column in my data for that. I'll be pulling it the same way I'm doing  
with year


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

True. But I do actually need to some date based calculations.  
Basically I'm processing a large data set and calculating time  
intervals between entries


>> 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.

Hmm, interesting. I need to think on that for a moment.  I may well  
have completely misunderstood a major part of Python all this time.

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

I expected a defaut value to be returned, perhaps "0". I see now from  
another response that this is not the case and so I've fixed it to read

print int(row['YEAR'] or 0000)

>
>> 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.

Thank you! I actually like the fact that it won't simply "fill  
something in". It makes things more predictable and stable.

Anthony


More information about the Python-list mailing list