开发者

Why is this python operation returning a tuple?

开发者 https://www.devze.com 2023-01-19 13:27 出处:网络
from datetime import date from datetime import timedelta a = date.today() - timedelta(1) # a above is a tuple and not datetime
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 th开发者_JS百科is 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


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.


Having looked at your image:

Why is this python operation returning a tuple?

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()


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号