Can I set a specific default time for a Django datetime field?
datetime, django, django-models, python
Solution
From the Django documents for `Field.default`:
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
So do this:
from datetime import datetime, timedelta
def default_start_time():
now = datetime.now()
start = now.replace(hour=22, minute=0, second=0, microsecond=0)
return start if start > now else start + timedelta(days=1)
class Something(models.Model):
timestamp = models.DateTimeField(default=default_start_time)
Problem
I have a model for events which almost always start at 10:00pm, but may on occasion start earlier/later. To make things easy in the admin, I'd like for the time to default to 10pm, but be changeable if needed; the date will need to be set regardless, so it doesn't need a default, but ideally it would default to the current date. I realize that I can use datetime.now to accomplish the latter, but is it possible (and how) to I set the time to a specific default value? Update: I'm getting answers faster than I can figure out which one(s) does what I'm trying to accomplish...I probably should have been further along with the app before I asked. Thanks for the help in the meantime!