我对夏令时处理感到有些困惑
settings.py:
TIME_ZONE = 'Europe/London'
USE_TZ = True
Run Code Online (Sandbox Code Playgroud)
在django shell中:
>>> from django.utils import timezone
>>> import datetime
>>> print timezone.now()
2012-05-28 11:19:42.897000+00:00
>>> print timezone.make_aware(datetime.datetime.now(),timezone.get_default_timez
one())
2012-05-28 12:20:03.224000+01:00
Run Code Online (Sandbox Code Playgroud)
为什么他们在夏令时方面不一样?两者都应该是语言环境,不是吗?
我已经阅读了文档但不是更明智的.
okm*_*okm 69
据timezone.now()
消息人士透露:
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()
Run Code Online (Sandbox Code Playgroud)
它基于utc
而不是您的默认时区.您可以通过使用获得相同的值
now = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timezone())
print now.astimezone(timezone.utc)
Run Code Online (Sandbox Code Playgroud)
vis*_*ell 17
从Django 1.11开始,您只需调用django.utils.timezone.localtime
fetch即可获取datetime
默认时区.
>>> from django.utils import timezone
>>> timezone.localtime()
Run Code Online (Sandbox Code Playgroud)
来自docs:
将感知日期时间转换为其他时区,默认为当前时区.
省略值时,默认为
now()
.此功能不适用于天真的日期时间; 使用
make_aware()
来代替.
您可以将参数传递给datetime.datetime.now()
:
import pytz, datetime
utc = pytz.utc
utc_now = datetime.datetime.now(tz=utc)
Run Code Online (Sandbox Code Playgroud)
或者使用timezone
,a:
from django.utils import timezone
now = timezone.now()
Run Code Online (Sandbox Code Playgroud)
https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/
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')
Run Code Online (Sandbox Code Playgroud)
如果您在 Django 设置中设置了TIME_ZONE = 'Europe/London'
and ,它将运行该部分,否则它将运行该部分。USE_TZ = True
try
except
[笔记]:
.strftime()
是一个选项