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?
DateTimeField – Django Models. DateTimeField is a date and time field which stores date, represented in Python by a datetime.datetime instance. As the name suggests, this field is used to store an object of datetime created in python. The default form widget for this field is a TextInput.
In django - is there a default timestamp field for all objects? That is, do I have to explicitly declare a 'timestamp' field for 'created on' in my Model - or is there a way to get this automagically? No such thing by default, but adding one is super-easy. Just use the auto_now_add parameter in the DateTimeField class:
from django.utils import timezone models.DateTimeField (default=timezone.now) Since you might be using IDs with your models, it's safe to use them this way. Then import the TimeStampedModel in any model you want to use them, eg
There is also model_utils for Django which contains already TimeStampedModel, but if you don't need anything else from this package, just keep it w/o extra weight. @boldnik I'm a fan of simplicity. Pretty cool... I have 3 classes that needed a timestamp for created and updated. This is a great way of doing it cleanly.
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With