Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DateTimeField()

In Django: I have a date and time that I need to enter into my database model, which has a column models.DateTimeField(). It seems that no matter what I do, I get a ValidationError: enter a valid date/time format.

I have a string like this:

myStr = "2011-10-01 15:26"

I want to do:

 p = mytable(myDate = WHAT_GOES_HERE)

 p.save()

Please don't point me to a duplicate question. I have looked around and they point to other questions which again point to questions, which point to some documentaton, which just doesn't get me what I need. Thanks!

like image 418
dkgirl Avatar asked May 02 '11 09:05

dkgirl


3 Answers

From the Django documentation:

# inserting datetime.now()
import django.utils.timezone as tz
mytable.objects.create(myDate=tz.localtime())

# inserting any date:
import pytz
import django.utils.timezone as tz
from datetime import datetime as dt
my_tz = pytz.timezone('Europe/Bucharest')
my_date = dt(2018, 8, 20, 0)
mytable.objects.create(myDate=tz.make_aware(my_date, my_tz))
like image 85
Tavy Avatar answered Sep 28 '22 16:09

Tavy


>>> import datetime
>>> myStr = "2011-10-01 15:26"
>>> WHAT_GOES_HERE = datetime.datetime.strptime(myStr, "%Y-%m-%d %H:%M")
>>> WHAT_GOES_HERE
datetime.datetime(2011, 10, 1, 15, 26)
>>> 
like image 32
dting Avatar answered Sep 28 '22 17:09

dting


datetime.strptime()

like image 45
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 17:09

Ignacio Vazquez-Abrams