Skip to content

Commit 9fdcbc3

Browse files
committed
Add time zone helpers for converting between local IETF db time and UTC
- Legacy-Id: 4849
1 parent 09e6203 commit 9fdcbc3

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

ietf/utils/timezone.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import pytz
2+
import email.utils
3+
import datetime
4+
5+
from django.conf import settings
6+
7+
def local_timezone_to_utc(d):
8+
"""Takes a naive datetime in the local timezone and returns a
9+
naive datetime with the corresponding UTC time."""
10+
local_timezone = pytz.timezone(settings.TIME_ZONE)
11+
12+
d = local_timezone.localize(d).astimezone(pytz.utc)
13+
14+
return d.replace(tzinfo=None)
15+
16+
def utc_to_local_timezone(d):
17+
"""Takes a naive datetime UTC and returns a naive datetime in the
18+
local time zone."""
19+
local_timezone = pytz.timezone(settings.TIME_ZONE)
20+
21+
d = local_timezone.normalize(d.replace(tzinfo=pytz.utc).astimezone(local_timezone))
22+
23+
return d.replace(tzinfo=None)
24+
25+
def email_time_to_local_timezone(date_string):
26+
"""Takes a time string from an email and returns a naive datetime
27+
in the local time zone."""
28+
29+
t = email.utils.parsedate_tz(date_string)
30+
d = datetime.datetime(*t[:6])
31+
32+
if t[7] != None:
33+
d += datetime.timedelta(seconds=t[9])
34+
35+
return utc_to_local_timezone(d)
36+
37+

0 commit comments

Comments
 (0)