Also ,how do I get the duration between two datetime.time objects ?I
tried to create two instances of these and can compare them using > or
< ,but found that - operation is not supported.Any tips are most
welcome
thanks
harry
Argument are only evaluated once, so `default=datetime.now().time` sets the default to the `datetime.now().time` as it is when evaluated. Once.
Just wrap the thing in a `lambda` and you should be good to go: `default=(lambda:datetime.now().time)`
any idea about calculating the duration? I can do a - between two
datetime.datetime objects to get a timedelta.. but that doesn't work
with datetime.time objects
harry
*defaults*, not arguments of course.
You have the option of converting to a datetime via time.strftime and datetime.strptime, even though it's ugly and probably quite inefficient:
>>> t
datetime.time(8, 56, 20, 653330)
>>> datetime.strptime(t.strftime('%H:%M:%S'), '%H:%M:%S')
datetime.datetime(1900, 1, 1, 8, 56, 20)
You don't even need to do this. Just remove the () from
datetime.now(), and it will do what you want it to.
If you pass in a callable as the default, this will be called each
time the object is created.
Matt.
Or use datetime.combine to combine both time objects with the same
date, and then add/subtract.
As Masklinn says, you hit overflow very easily with addition and
subtraction of time objects/timedeltas. For instance, even with a
short timedelta:
datetime.time(20,0) + datetime.timedelta(hours=3)
What is the value of this expression? datetime.time cannot exceed
datetime.time(23,59,59). Does it tick over to (0,0,0) again.
Sorry, bad pun.
[I actually have a use case similar to this - where the values I store
are open/close times. Sometimes, the close time can be earlier than
the open time, if the shop is open past midnight. It gets messy
quickly].
Except in this case he wants a `time` object, not a `datetime` one. Are you sure Django handles the coercion/conversion from `datetime` to `time`?
Sorry, my mistake. For some reason I thought there was a
datetime.time.now() method.
The lambda is the best solution.