forked from adamlaska/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimezone.py
More file actions
39 lines (26 loc) · 1.1 KB
/
timezone.py
File metadata and controls
39 lines (26 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import pytz
import email.utils
import datetime
from django.conf import settings
def local_timezone_to_utc(d):
"""Takes a naive datetime in the local timezone and returns a
naive datetime with the corresponding UTC time."""
local_timezone = pytz.timezone(settings.TIME_ZONE)
d = local_timezone.localize(d).astimezone(pytz.utc)
return d.replace(tzinfo=None)
def utc_to_local_timezone(d):
"""Takes a naive datetime UTC and returns a naive datetime in the
local time zone."""
local_timezone = pytz.timezone(settings.TIME_ZONE)
d = local_timezone.normalize(d.replace(tzinfo=pytz.utc).astimezone(local_timezone))
return d.replace(tzinfo=None)
def email_time_to_local_timezone(date_string):
"""Takes a time string from an email and returns a naive datetime
in the local time zone."""
t = email.utils.parsedate_tz(date_string)
d = datetime.datetime(*t[:6])
if t[7] != None:
d += datetime.timedelta(seconds=t[9])
return utc_to_local_timezone(d)
def date2datetime(date, tz=pytz.utc):
return datetime.datetime(*(date.timetuple()[:6]), tzinfo=tz)