[Answer]-Would DateTimeField() work if I have time in this format 1/7/11 9:15 ? If not what would?



β€œWhat would be the best variable type/format to define in order to accept this date as it is?”

The DateTimeField.

β€œIf not what would be the most efficient way to accomplish this task?”

You should use the datetime.strptime method from Python’s builtin datetime library:

>>> from datetime import datetime
>>> import json

>>> json_datetime = "1/7/11 9:15"  # still encoded as JSON
>>> py_datetime = json.loads(json_datetime)  # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M")  # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)

# Now you can save this object to a DateTimeField in a Django model.
πŸ‘€Brian Dant


If you take a look at https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield, it says that django uses the python datetime library which is docomented at http://docs.python.org/2/library/datetime.html.

Here is a working example (with many debug prints and step-by-step instructions:

from datetime import datetime

json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime

#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style

Leave a comment