django 1.4 timezone.now() vs datetime.datetime.now()

前端 未结 4 1985
自闭症患者
自闭症患者 2020-12-08 06:03

I\'m a bit confused by the daylight savings handling

settings.py:

TIME_ZONE = \'Europe/London\'
USE_TZ = True

in the django shell:<

相关标签:
4条回答
  • 2020-12-08 06:50

    Since Django 1.11 you can simply call django.utils.timezone.localtime to fetch datetime for your default timezone.

    >>> from django.utils import timezone
    >>> timezone.localtime()
    

    From docs:

    Converts an aware datetime to a different time zone, by default the current time zone.

    When value is omitted, it defaults to now().

    This function doesn’t work on naive datetimes; use make_aware() instead.

    0 讨论(0)
  • 2020-12-08 06:55
    from datetime import datetime
    from django.utils import timezone
    
    def now():
        try:
            return timezone.localtime(timezone.now()).strftime('%Y-%m-%dT%H:%M:%S')
    
        except Exception as exp:
            print('TimeZone is not set - {}'.format(exp))
            return datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
    

    If you set TIME_ZONE = 'Europe/London' and USE_TZ = True in Django setting, you will place in the try section and else, in the except section.


    [NOTE]:

    • .strftime() is an option
    0 讨论(0)
  • 2020-12-08 07:09

    According to timezone.now() source:

    def now():
        """
        Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
        """
        if settings.USE_TZ:
            # timeit shows that datetime.now(tz=utc) is 24% slower
            return datetime.utcnow().replace(tzinfo=utc)
        else:
            return datetime.now()
    

    It's based on utc instead of your default timezone. You could achieve same value by using

    now = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timezone())
    print now.astimezone(timezone.utc)
    
    0 讨论(0)
  • 2020-12-08 07:09

    You can pass a param to datetime.datetime.now():

    import pytz, datetime
    utc = pytz.utc
    utc_now = datetime.datetime.now(tz=utc)
    

    Or use timezone, a la:

    from django.utils import timezone
    
    now = timezone.now()
    

    https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/

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