Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - DateTimeField received a naive datetime

Basically I have the following model:

class Event(models.Model):
    start = models.DateTimeField(default=0)

and when I try to create an object using datetime.datetime.strptime I get

Event.objects.create(start=datetime.datetime.strptime("02/03/2014 12:00 UTC",
                                                      "%d/%m/%Y %H:%M %Z"))

/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py:903: 
RuntimeWarning: DateTimeField Event.start received a naive datetime (2014-03-02 
12:00:00) while time zone support is active.

I've gone through many post similar to this, but I can't figure out why it gives an error eventhough I'm putting the UTC (%Z) argument.

Thanks in advance.

like image 855
user3264316 Avatar asked Feb 25 '14 22:02

user3264316


2 Answers

That warning is logged since you are using time zones and you are creating a datetime object "manually". I also suggest you to turn the warning into an error by adding:

import warnings
warnings.filterwarnings('error',
                        r"DateTimeField .* received a naive datetime",
                        RuntimeWarning, r'django\.db\.models\.fields')

in your settings.py, in this way you can spot such irregularities more easily.

Honestly I don't know why, but actually your date seems unaware (if you use timezone.is_aware() it should return false).

To fix your current code I suggest you to rely on django utilis for timezones:

from django.utils import timezone
timezone.make_aware(yourdate, timezone.get_current_timezone())

For my project I created an utility class for dates, since I was facing such problems, you can take a look (especially to the method dateFromString):

class DateUtils(object):

    @classmethod
    def currentTimezoneDate(cls):
        """
        Returns an aware datetime object based on current timezone.

        :return: datetime: date
        """
        return timezone.make_aware(datetime.now(), timezone.get_current_timezone())


    @classmethod
    def currentTimezoneOffset(cls):
        """
        Returns the offset (expressed in hours) between current timezone and UTC.

        :return: int: offset
        """
        offset = cls.currentTimezoneDate().utcoffset()
        return int(offset.total_seconds() / 60 / 60)


    @classmethod
    def UTCDate(cls, year, month, day, hour=0, minute=0, second=0, microsecond=0):
        """
        Creates an aware UTC datetime object.

        :return: datetime: date
        """
        d = datetime(year, month, day, hour, minute, second, microsecond)
        return timezone.make_aware(d, timezone.utc)


    @classmethod
    def asUTCDate(cls, date):
        """
        Get the UTC version of the given date.

        :param date: datetime: Date to be converted into UTC
        :return: datetime UTC date
        """
        if type(date) is Date:
            return timezone.make_aware(datetime(date.year, date.month, date.day), timezone.utc)
        if not timezone.is_aware(date):
            return timezone.make_aware(date, timezone.utc)
        return date.replace(tzinfo=timezone.utc)


    @classmethod
    def getJavaScriptDateFormatForCurrentLocale(cls):
        """
        Return a date mask string that will be understood and used by JavaScript.

        :return: str: Date mask string for JavaScript.
        """
        f = get_format('SHORT_DATE_FORMAT')
        return f.replace('Y', 'yyyy').replace('m', 'mm').replace('d', 'dd')


    @classmethod
    def getPythonDateFormatForCurrentLocale(cls):
        """
        Return a date mask string that will be understood and used by Python.

        :return: str: Date mask string for Python.
        """
        f = get_format('SHORT_DATE_FORMAT')
        return f.replace('Y', '%Y').replace('m', '%m').replace('d', '%d')


    @classmethod
    def dateFromString(cls, string, format=None, utc=True):
        """
        Returns a datetime object from the given string.

        :param string: str: A date string
        :param format: str: The format of the date
        :return: datetime: date
        """
        date = datetime.strptime(string, format or cls.getPythonDateFormatForCurrentLocale())
        if utc:
            return cls.asUTCDate(date)
        return date


    @classmethod
    def getFormattedStringForCurrentLocale(cls, date):
        """
        Return a date string formatted using current locale settings.

        :param date: datetime:
        :return: str: Formatted Date string.
        """
        return date.strftime(cls.getPythonDateFormatForCurrentLocale())


    @classmethod
    def randomDate(cls, start, end):
        """
        Return a random date between the 2 dates provided.
        See: http://stackoverflow.com/a/8170651/267719

        :param start: datetime: Min date.
        :param end: datetime: Max date.
        :return: datetime: Random date in range.
        """
        return start + timedelta(seconds=randint(0, int((end - start).total_seconds())))


    @classmethod
    def hourRange(cls, fromHour, toHour):
        n = fromHour
        hRange = [fromHour]
        while n != toHour:
            n += 1
            if n > 23:
                n = 0
            hRange.append(n)
        hRange.pop()
        return hRange 
like image 119
daveoncode Avatar answered Oct 03 '22 18:10

daveoncode


You need to use Django's make_aware() function.

from django.utils import timezone
#....

aware_date = timezone.make_aware(datetime.strptime("02/03/2014 12:00 UTC", "%d/%m/%Y %H:%M %Z"), \
                                  timezone.get_default_timezone())
like image 25
kmonsoor Avatar answered Oct 03 '22 19:10

kmonsoor