duration = timesheet.end_time - timesheet.start_time
当您减去两个datetime实例时,您不会得到另一个datetime实例,但是
timedelta
instace,这只是两个日期之间的天、秒和微秒差。不能在DateTimeField中存储TimeDelta,但可以使用IntegerField,例如:
days_in_seconds = duration.days * 86400 # days difference by seconds in a day
duration_in_seconds = duration.seconds + days_in_seconds # duration in seconds
当您想以timedelta形式访问持续时间时,只需执行以下操作:
import datetime
duration = datetime.timedelta(seconds=timesheet.duration)
您还可以将其存储为floatfield,如下所示
question
.