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

django datetimefield
set default time django
django timefield
django set datetime field
django datetime set time
set default datetime in django
django datetimefield default null
django time field with timezone

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!

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)

How can I set a DateField format in django from the model?, is a NumberInput when localize is False or TextInput otherwise. TimeField is a time field which stores time, represented in Python by a datetime.time instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput. The admin uses two separate TextInput widgets with JavaScript shortcuts. Syntax

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))

How do I display current time using Python + Django?, Automatically set the field to now every time the object is saved. For TimeField: default=datetime.time.now – from datetime.now() If the verbose name isn't given, Django will automatically create it using the field's attribute name, converting  Both Django’s DateTimeField and DateField have two very useful arguments for automatically managing date and time. If you want keep track on when a specific instance was created or updated you don’t need to do it manually: just set the auto_now and auto_now_add arguments to True like in the following example: class Invoice (models.

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

IntegerField - Django Models, But how do you make sure that every time a new object is created they receive the current date and time? That's easy: just set the default option  # app/models.pyfrom django.db import modelsfrom datetime import datetimeclass Book(models.Model):name = models.CharField(max_length=128)release_date = models.DateTimeField(default=datetime.now())

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

TimeField - Django Models, db_column: The db_column specified in the model (or None). # * column: Code that introspects values, or does other dynamic things, should use # attname​. hint='It seems you set a fixed date / time / datetime ' 'value as default for this field. 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.

Something like this?

import datetime

dt = datetime.now()
dt.hour = 22
dt.minute = 0
dt.second = 0

Hard to be more specific without context.

How to Properly Set a Default Value for a DateTimeField in Django , A value beginning with a period can be used as a subdomain wildcard: '.example​.com' will match example.com This is a PostgreSQL-specific setting. The default formatting to use for displaying datetime fields in any part of the system. When I use the .create() method on the model, I pass in a specific datetime to the DateTimeField but it gets ignored and overwritten by the auto_now_add functionality. The only way I can do what I want is by first creating, then altering the value on the DateTimeField, then saving a second time to override.

django.db.models.fields | Django documentation, Because the time is set by calling datetime.now() in the pre_save method of the field, Record transaction start time in Django (something like PostgreSQL now​()); Use this ticket now that we can use ​database functions, e.g. default=NOW . # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'.

Settings | Django documentation, Given the datetime 2015-06-15 23:30:01.000321+00:00 , the built-in Since DateField s don't have a time component, only Extract subclasses that a datetime, date, or time depending on output_field , with fields up to kind set to their minimum value. If output_field is omitted, it will default to the output_field of expression . The datetime module of Python offers classes for manipulating dates and times easily. You can format any date of Python (as long as it is a datetime object) using the strftime method. Date formatting. A datetime object will have the method strftime that allows you to provide a custom format to a date and print it as a string wherever you need

#16745 (Different times on fields with auto_now and auto_now_add , When I use the .create() method on the model, I pass in a specific datetime to the The only way I can do what I want is by first creating, then altering the value on the DateTimeField, then saving a second time to override. Any other field that has a default can be overridden. Zen of Python; You know what I mean. A DateTimeFieldhas two optional parameters: auto_now_addsets the value of the field to current datetime when the object is created. auto_nowsets the value of the field to current datetime every time the field is saved. These options and the defaultparameter are mutually exclusive.

Comments
  • I'm getting 'TypeError: __init__() got an unexpected keyword argument 'default''. Any ideas? Using a forms.Form instead of a model form. forms.TimeField(default=dt.time(16, 0), widget=forms.TimeInput)
  • I like how this example uses "tomorrow at 10pm" if the model instance is created after 10pm.
  • when you are using datetime.now() instead of datetime.now now will be a fixed date, when that is first evaluated. What does that mean? When your server runs for a weak, with datetime.now() it will always be the date when the server was started. With using datetime.now it will be dynamicely evaluated.
  • is it possible to just show the hours and minutes when displayed on the screen rather than show the hours minutes and milliseconds. and rather than use military time, use am and pm... because with what you have above it shows the full time.
  • Not sure why you'd want to include datetime.datetime in a TimeField. Better to do start= models.TimeField(default=datetime.time(16, 00))
  • I'm not sure what more context I could give; I just want the person entering the date in to not have to change it to 10:00 every single time they add a new event (but still have the option to change it). The solution is admittedly simple if there is one; that looks like it might work.