python 减去两个日期得到一个时间增量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2238008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtract two dates to give a timedelta
提问by Stephen
I'm trying to get a value from one of my database values, which will be given by subtracting the purchase date from today's date. I've written my code this way:
我正在尝试从我的数据库值之一中获取一个值,该值将通过从今天的日期中减去购买日期来给出。我是这样写我的代码的:
delta = datetime.now() - item.purchase_date
But this gives me this error:
但这给了我这个错误:
unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
If I use datetime.datetime.now()
this doesn't work. What am I missing. Thanks.
如果我使用datetime.datetime.now()
它不起作用。我错过了什么。谢谢。
回答by SilentGhost
you need to use date.today
or datetime.now().date()
instead of datetime.now
:
您需要使用date.today
或datetime.now().date()
代替datetime.now
:
>>> import datetime
>>> datetime.date.today()
datetime.date(2010, 2, 10)
>>> datetime.datetime.now().date()
datetime.date(2010, 2, 10)