python - Django - DateTimeField 收到一个天真的日期时间

标签 python django datetime

基本上我有以下模型:

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

当我尝试使用 datetime.datetime.strptime 创建一个对象时,我得到了

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.

我浏览过许多与此类似的帖子,但我无法弄清楚为什么即使我输入了 UTC (%Z) 参数也会出现错误。

提前致谢。

最佳答案

该警告已记录,因为您正在使用时区并且正在“手动”创建日期时间对象。我还建议您通过添加以下内容将警告变成错误:

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

在您的 settings.py 中,通过这种方式您可以更轻松地发现此类违规行为。

老实说我不知道​​为什么,但实际上你的日期似乎并不知道(如果你使用 timezone.is_aware() 它应该返回 false)。

要修复您当前的代码,我建议您依赖 django utilis 来处理时区:

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

对于我的项目,我创建了一个日期实用类,因为我遇到了这样的问题,你可以看看(特别是方法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 

关于python - Django - DateTimeField 收到一个天真的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028004/

相关文章:

python - ubuntu python 3.4 没有站点包库

python - 在 Sphinx 自动摘要中使用第一段而不是第一行

python - 将 2 个给定日期之间的天数拆分为特定的批量大小,并相应地获取开始日期和结束日期

javascript将日期和时间转换为特定格式

sql - 如何在 SQL Server 中以毫秒为单位打印 GETDATE()?

python - 获取列值出现后的所有行 pandas

python - 如何解析python中的括号树?

python - Django manage.py runserver 抛出 ImportError : AdminMediaHandler

python - 帖子中的评论

python - 使用 render_to_string 时填充 {% csrf_token %}?