Reputation: 13
Using Python/Django 1.5.4, I am trying to find a way of getting the current time in London, UK.
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.
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?
Upvotes: 0
Views: 1942
Reputation: 414745
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.
In django
, set USE_TZ=True
and use timezone.now()
to get the current time in UTC as an aware datetime object. 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
.
Upvotes: 1
Reputation: 918
Instead of using time.time(), datetime.now(), datetime.utcnow(), when in django use from django.utils import timezone and use timezone.now
. This is specifically designed to handle such scenarios in django. For further reading check here.
Upvotes: 1