8

Django newbie here. I am crafting a Django model for a SQLite database with string timestamps, e.g. 2014-09-23T18:43:26.692Z. Because I would like to eventually use Django's filtering engine for queries (instead of using strftime), I want my model to generate DateTimeField objects from ISO strings. If I try to declare a DateTimeField on the raw DB field like this

startTime = models.DateTimeField(db_column='startTime')

I get an error: 'unicode' object has no attribute 'isoformat'

I did some digging and tried the following code:

startTime = models.DateTimeField(dateutil.parser.parse(models.TextField(db_column='startTime'))

But now the error is AttributeError: 'TextField' object has no attribute 'read'. What am I doing wrong? Is this even the right approach?

1
  • 1
    django's ORM has a pretty powerful date manipulation support. I would not change that. If there are any specific things you are thinking of, do edit the question to see if there is a standard way of doing it.
    – karthikr
    Sep 26, 2014 at 16:06

2 Answers 2

32

Since nobody bothered to answer this and it showed up at the top of a Google search, here's to save some extra searching.. As someone mentioned Django's own dateparse module is best for the job and converts ISO8601 and many other formats to Python's datetime.datetime object. Also it's timezone aware and hence ideal for Django projects.

from django.utils import dateparse

x = '2014-09-23T18:43:26.692Z'
y = dateparse.parse_datetime(x)
print y

And voila..!

2014-09-23 18:43:26.692000+00:00
1

It seems in Django 1.11, we could just assign a ISO format string to DateTimeField . like the following shows.

Lesson.objects.create(starttime='2017-04-20T12:01:00.000Z',
                      endtime  ='2017-04-20T13:01:00.000Z')
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.