tags:

views:

100

answers:

4
from datetime import date
from datetime import timedelta

a = date.today() - timedelta(1)
# a above is a tuple and not datetime
# Since I am a C programmer, I would expect python to cast back to datetime
# but it is casting it to a tuple

Can you please tell me why this is happening? and also how I can see that the operation above results in a datetime?

I am a python newbie, sorry if this is a trivial thing, but I am stuck here for a while!

Thanks

+1  A: 

use type built-in function:

>>> from datetime import date
>>> from datetime import timedelta
>>> 
>>> a = date.today() - timedelta(1)
>>> a
datetime.date(2010, 10, 8)
>>> type(a)
<type 'datetime.date'>
>>> 
Kimvais
+5  A: 

Perhaps the repr of a confuses you:

>>> a
datetime.date(2010, 10, 8)

this is not a tuple, it's what datetime uses as repr(). Print it to get its string() representation:

>>> print a
2010-10-08

Either str() a yourself explicitly or use a.strftime() to do you own formatting.

Ivo van der Wijk
+3  A: 

Having looked at your image: Python code screenshot

I think you are assuming it's a string, because print outputs a string - but that's exactly what its job is! The object is a datetime. You cannot convert it to a date by passing it to the date() constructor, either - instead you should call a.date()

Evgeny
Thanks! There was another bug in my code. Fixed it
arbithero
I have no idea where the -2 came from. Anyone care to explain what's wrong with this answer?
Evgeny
A: 

Your statement

date.today() - timedelta(1)

returns a date object.

This object have two string representations:

  • The most common readable format is by calling str() function (the same called using print), in this case str(a) gives you '2010-10-08'

  • A second representation, the object nature, is by using repr() function. In this case repr(a) returns 'datetime.date(2010, 10, 8)'.

systempuntoout