I have a Django app with a model that contains a field of type DateTimeField.
I am pulling data from the web in the format of 2008-04-10 11:47:58-05.
I believe that the last 3 characters in this example are the timezone.
How can I preserve that data in the DateTimeField, and is there an easy conversion between the two? Setting the DateTimeField to simply contain a string of the above format throws a ValidationError.

Thank you!

up vote 35 down vote accepted

You can use

import dateutil.parser
dateutil.parser.parse('2008-04-10 11:47:58-05')

Which returns a datetime (that can be assigned to the DateTimeField).

  • this sounds great, but in my python 2.6.5 there is no datetime.parser or datetime.datetime.parser modules (I get an ImportError). What am I missing? – user1094786 Dec 26 '11 at 16:26
  • AH crap! Of course I mean "dateutil". Post updated! – nisc Dec 26 '11 at 18:14
  • Just wondering, does this work? – nisc Dec 31 '11 at 16:44
  • 16
    Note that dateutil is a third-party module (see python-dateutil on PyPI), which you may not have installed by default. – Pi Delport Jul 30 '12 at 12:30
  • perfect, thanks! It figured out my string date format, great time saver. – Bogatyr Sep 26 '14 at 18:01

You can also use Django's implementation. I would in fact prefer it and only use something else, if Django's parser cannot handle the format.

For example:

>>> from django.utils.dateparse import parse_datetime
>>> parse_datetime('2016-10-03T19:00:00')
datetime.datetime(2016, 10, 3, 19, 0)
>>> parse_datetime('2016-10-03T19:00:00+0200')
datetime.datetime(2016, 10, 3, 19, 0, tzinfo=<django.utils.timezone.FixedOffset object at 0x8072546d8>)

To have it converted to the right timezone when none is known, use make_aware from django.utils.timezone.

So ultimately, your parser utility would be:

from django.utils.dateparse import parse_datetime
from django.utils.timezone import is_aware, make_aware

def get_aware_datetime(date_str):
    ret = parse_datetime(date_str)
    if not is_aware(ret):
        ret = make_aware(ret)
    return ret
  • 4
    This should be the accepted answer. – Dan Gayle Oct 6 '14 at 23:07
  • 1
    I sure wish the docs specified exactly what a 'well formatted' date is, though! I would expect that to mean RFC 1123, but it doesn't seem to like what my browser is sending back... – Michael Scheper Nov 18 '14 at 11:21
  • This answer is not correct in that a timezone aware datetime is not returned, at least not in 1.8.4. You can try this for yourself from django.utils import timezone, dateparse; timezone.is_aware(dateparse.parse_datetime('2015-09-04 19:22:17')) and also see in the source that a datetime.datetime is returned. – Jmills Aug 27 '15 at 15:49
  • @TheCardCheat You're right that it doesn't make_aware() (github tells me it never did and yet code I used became aware somewhere). But, if an input string contains a timezone offset that is recognized then it does return an aware datetime. – Melvyn Sep 23 '16 at 12:51

I've been using this:

from django.utils.timezone import get_current_timezone
from datetime import datetime
tz = get_current_timezone()
dt = tz.localize(datetime.strptime(str_date, '%m/%d/%Y'))

If you're using Django Forms, you can specify input_formats to your DateField. See the DateField documentation

If you are wanting to parse arbitrary date information, you could use something like parsedatetime and implement a method that Django calls to do the parsing before it hits the validators. (See this SO answer for a good summary of how validations work and when to insert them)

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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