0

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?

  • You should definitely not be using Django 1.5. It has been unsupported for quite some time and is probably subject to lots of security issues. Upgrade to 1.8 at a minimum. – Daniel Roseman Dec 02 '15 at 10:50
  • 1
    GMT doesn't have DST. Did you mean GMT vs. BST? – Ignacio Vazquez-Abrams Dec 02 '15 at 10:50
  • However the answer to your question is almost certainly found in the comprehensive [documentation on timezones](https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/). – Daniel Roseman Dec 02 '15 at 10:50
  • Try and check this answer: http://stackoverflow.com/questions/1398674/python-display-the-time-in-a-different-time-zone – toti08 Dec 02 '15 at 11:13
  • Thanks a lot. Yeah, Django 1.5... tell me about it..! In the process of migrating a large project to a more recent version. – Ali Skinner Dec 02 '15 at 15:35

2 Answers2

1

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.

Tarun Behal
  • 908
  • 6
  • 11
  • Thanks. This is what I ended up doing – Ali Skinner Dec 02 '15 at 15:35
  • 1
    @AliSkinner: you should set `USE_TZ=True` (it is set if `settings.py` is generated by `django-admin startproject`) so that `timezone.now()` would return a timezone-aware datetime object (in UTC timezone that may be different from London time). Set `TIME_ZONE=Europe/London` so that London time would be the default while rendering time in templates (use `.activate()` to change a per request current time zone). – jfs Dec 02 '15 at 19:46
  • @AliSkinner if you think this is the best approach to your issue, please accept the answer so others can be benefited from the same. Thanks.. – Tarun Behal Dec 03 '15 at 06:25
1

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670