[英]How to get daylight-saving-aware GMT
Using Python/Django 1.5.4, I am trying to find a way of getting the current time in London, UK. 我正在尝试使用Python / Django 1.5.4,找到一种获取英国伦敦当前时间的方法。
It seems to be surprisingly complicated to do so. 这样做似乎很复杂。
Obviously there is the time.time(), datetime.now(), datetime.utcnow(), but these methods return the server time. 显然有time.time(),datetime.now(),datetime.utcnow(),但是这些方法返回服务器时间。
This is a problem because the server may not be in the UK and the above methods don't take daylight saving into account. 这是一个问题,因为该服务器可能不在英国,并且上述方法未考虑夏令时。
Is there a simple, straightforward way of doing this without excessive imports and third-party apps? 是否有一种简单,直接的方法来执行此操作,而无需过多的导入和第三方应用程序?
Instead of using time.time(), datetime.now(), datetime.utcnow(), when in django use from django.utils import timezone and use timezone.now
. 在django中时,
from django.utils import timezone and use timezone.now
,而不是使用time.time(),datetime.now(),datetime.utcnow()。 This is specifically designed to handle such scenarios in django. 这是专门为处理django中的此类情况而设计的。 For further reading check here .
如需进一步阅读,请点击此处 。
To get the current time in London, UK: 要获取英国伦敦的当前时间:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
print(datetime.now(pytz.timezone('Europe/London')))
It works correctly even during DST transitions when the local time may be ambiguous. 即使在当地时间可能不明确的DST转换期间,它也可以正常工作。
In django
, set USE_TZ=True
and use timezone.now()
to get the current time in UTC as an aware datetime object. 在
django
,设置USE_TZ=True
并使用timezone.now()
来获取UTC中的当前时间作为USE_TZ=True
datetime对象。 It is rendered in templates using the current time zone that you could set using .activate()
otherwise the default time zone is used that is defined by TIME_ZONE
. 它使用您可以使用
.activate()
设置的当前时区在模板中呈现,否则使用由TIME_ZONE
定义的默认时区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.