Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format for DateTimeField [duplicate]

Tags:

python

django

Possible Duplicate:
Converting string into datetime

In Django I get this error "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." when I try to assign a string "22-DEC-2009" to a DateTimeField in a model.

How is it possible to make DateTimeField accept a date string in format "22-DEC-2009"?

like image 211
Vishal Avatar asked Apr 22 '26 14:04

Vishal


1 Answers

You can pass the input formats as input_formats argument to DateTimeField, so you can do this

# you can keep a list of formats yourself, or copy from django 1.2 version e.g.
# my_formats = fields.DEFAULT_DATETIME_INPUT_FORMATS + ['%d-%b-%Y']
# for latest django use this
from django.utils.formats import get_format
my_formats = get_format('DATETIME_INPUT_FORMATS')
field = DateTimeField(input_formats=my_formats,...)

If instead you directly want to assign a date-str to models.DateTimeField best way is to just convert it to datetime before hand e.g.

mymodel.date_of_birth = datetime.datetime.strptime("22-DEC-2009", "%d-%b-%Y")
like image 190
Anurag Uniyal Avatar answered Apr 25 '26 03:04

Anurag Uniyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!