简体   繁体   English

在python2.7 / django1.5.1中遇到日期时间问题

[英]Trouble with datetime in python2.7/django1.5.1

I'm trying to get the number of days in between the current date and a fixed date set in the past. 我正在尝试获取当前日期和过去设定的固定日期之间的天数。

from datetime import *

past = date(2013, 1, 1)
now = datetime.now()

print now - past

When I run this, I get: 当我运行这个时,我得到:

TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'

Any suggestions are appreciated. 任何建议表示赞赏。

Use a datetime.date() object instead. 请改用datetime.date()对象 You can use date.today() , or call the datetime().date() method : 您可以使用date.today() ,或调用datetime().date()方法

>>> from datetime import datetime, date
>>> past = date(2013, 1, 1)
>>> today = date.today()
>>> print today - past
385 days, 0:00:00
>>> now = datetime.now()
>>> print now.date() - past
385 days, 0:00:00

The result of the subtraction is a datetime.timedelta() object , with timedelta().seconds and timedelta().microseconds set to 0 , always. 减法的结果是datetime.timedelta()对象timedelta().secondstimedelta().microseconds总是设置为0 The .days attribute gives you just that number of days between the dates: .days属性为您提供日期之间的天数:

>>> print (today - past).days
385
>>> print (now.date() - past).days
385

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM