I have an object with a model.DateTimeField on it. For various reasons, I
need to set the time portion of this field to 23:59 when I populate it from a
form.
datetime = models.DateTimeField()
How can I do this? I've tried
self.datetime = pForm.cleaned_data['datetime']
self.datetime.replace(hour=23, minute=59)
but hour isn't accepted as a parameter to replace.
I'm also confused as to how the DateTimeField maps on to a python datetime
object, can anyone educate me?
Thanks,
Tim.
Hmm, that seemed to make sense to me too, though with my Java background I
wasn't sure. I get:
Exception Value: 'hour' is an invalid keyword argument for this function
on
self.datetime = self.datetime.replace(hour=23, minute=59)
self.datetime is defined as:
datetime = models.DateTimeField()
Cheers,
Tim.
Sussed it.
In my code, I did this:
self.datetime = pForm.cleaned_data['datetime']
the datetime parameter passed from the form only contained the date, with no
time, so I assume the value in datetime then was only a date.
I've sorted my problem using the following code:
self.datetime = datetime(self.datetime.year, self.datetime.month,
self.datetime.day, 23, 59)
Thanks for your help,
Tim.
This shouldn't happen: a DateTimeField normalizes to a
datetime.datetime object. Are you sure you're not using a DateField
in your form?
Arien
Well spotted.
In my form I have:
datetime =
forms.DateField(widget=forms.TextInput({'class' : 'date-pick'}),label="Available
date")
yet it's a DateTimeField in the model.
This means that the reason that the value fetched from the form is only a date
is because of the type in the form. Assigning this date only value from the
form to the model attribute means I can't use replace(hour=23) on it any
more. I don't really understand why, but I'm sure there's a logical
explanation!
Tim.
Why not use a DateTimeField in your form and change the widget
instead? For example:
datetime = forms.DateTimeField(
widget=forms.DateTimeInput(format='%Y-%m-%d', attrs={'class' :
'date-pick'}),
label="Available date"
)
(Note the attrs={...} for the class.)
> This means that the reason that the value fetched from the form is only a date
> is because of the type in the form. Assigning this date only value from the
> form to the model attribute means I can't use replace(hour=23) on it any
> more. I don't really understand why, but I'm sure there's a logical
> explanation!
The logical explanation is that adjusting the hour of a date doesn't
make sense, because a date doesn't have any hour. ;-)
Arien