Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a specific default time for a Django datetime field?

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!

like image 545
lisaq Avatar asked Apr 16 '13 01:04

lisaq


People also ask

What is Django default datetime format?

django default date to be in format %d-%m-%Y.

How do I change the date automatically changes in a value in Django?

You want to add the auto_now field and set it to True. This will update with the current timestamp each time you update the model.

What is time field in Django?

TimeField in Django Forms is a time input field, for input of time for particular instance or similar. The default widget for this input is TimeInput. It validates that the given value is either a datetime. time or string formatted in a particular time format.


4 Answers

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)
like image 136
tobych Avatar answered Oct 12 '22 05:10

tobych


in case you're interested into setting default value to TimeField: https://code.djangoproject.com/ticket/6754

don't:

start = models.TimeField(default='20:00')

do instead:

import datetime
start = models.TimeField(default=datetime.time(16, 00))
like image 29
Bruno Gelb Avatar answered Oct 12 '22 06:10

Bruno Gelb


datetime.time(16, 00) does not work.

Use datetime.time(datetime.now()) instead if you are trying to get the current time or datetime.time(your_date_time)

Where your_date_time = datetime.datetime object

like image 4
Oluwafemi Tairu Avatar answered Oct 12 '22 07:10

Oluwafemi Tairu


Have you seen this? https://docs.djangoproject.com/en/dev/ref/models/fields/#default

That's probably what you're looking for.

It's also discussed here: Default value for field in Django model

like image 1
davidtheclark Avatar answered Oct 12 '22 06:10

davidtheclark