django 1.4 - can't compare offset-naive and offset-aware datetimes

前端 未结 1 1893
野趣味
野趣味 2020-12-02 06:00

I am in the process of migrating an application from django 1.2 To 1.4.

I have a daily task object which contains a time of day that task should be completed:

<
相关标签:
1条回答
  • 2020-12-02 06:40

    Check the thorough document for detail info.

    Normally, use django.utils.timezone.now to make an offset-aware current datetime

    >>> from django.utils import timezone
    >>> timezone.now()
    datetime.datetime(2012, 5, 18, 13, 0, 49, 803031, tzinfo=<UTC>)
    

    And django.utils.timezone.make_aware to make an offset-aware datetime

    >>> timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone())
    datetime.datetime(2012, 5, 18, 21, 5, 53, 266396, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
    

    You could then compare both offset-aware datetimes w/o trouble.

    Furthermore, you could convert offset-awared datetime to offset-naive datetime by stripping off timezone info, then it could be compared w/ normal datetime.datetime.now(), under utc.

    >>> t = timezone.now() # offset-awared datetime
    >>> t.astimezone(timezone.utc).replace(tzinfo=None)
    datetime.datetime(2012, 5, 18, 13, 11, 30, 705324)
    

    USE_TZ is True 'by default' (actually it's False by default, but the settings.py file generated by django-admin.py startproject set it to True), then if your DB supports timezone-aware times, values of time-related model fields would be timezone-aware. you could disable it by setting USE_TZ=False(or simply remove USE_TZ=True) in settings.

    0 讨论(0)
提交回复
热议问题