|
0
|
1 |
from datetime import timedelta |
|
275
|
2 |
from pytz import timezone, utc, UnknownTimeZoneError |
|
0
|
3 |
from django.conf import settings |
|
|
4 |
|
|
|
5 |
local_tz = timezone(settings.TIME_ZONE) |
|
|
6 |
|
|
|
7 |
def request_tz_convert(date, request): |
|
|
8 |
return tz_convert(date, request.session.get('tz',None)) |
|
|
9 |
|
|
|
10 |
def tz_convert(date, tz): |
|
|
11 |
""" |
|
|
12 |
Convert date to time zone |
|
|
13 |
tz can be; |
|
|
14 |
- '-2' (relative to utc) |
|
|
15 |
- 'Paris/Europe' real timezone like (cf pytz) |
|
|
16 |
""" |
|
|
17 |
if tz: |
|
|
18 |
system_local_date = local_tz.localize(date) |
|
|
19 |
try: |
|
|
20 |
# simple utc delta? |
|
|
21 |
utc_offset = int(tz) |
|
|
22 |
utc_time = system_local_date.astimezone(utc) |
|
|
23 |
res = utc.normalize(utc_time + timedelta(hours=utc_offset)) |
|
|
24 |
return res |
|
|
25 |
except: |
|
275
|
26 |
try: |
|
|
27 |
# real timezone |
|
|
28 |
timez = timezone(tz) |
|
|
29 |
local_date = system_local_date.astimezone(timez) |
|
|
30 |
return local_date |
|
|
31 |
except UnknownTimeZoneError: |
|
|
32 |
# fall back to date |
|
|
33 |
return date |
|
|
34 |
|
|
0
|
35 |
else: |
|
|
36 |
return date |