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

前端 未结 4 1996
自闭症患者
自闭症患者 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: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

提交回复
热议问题