2
2
import os
3
3
import dateutil
4
4
import tzlocal
5
-
6
- DEFAULT_TIME_ZONE_NAME = tzlocal .get_localzone ().zone # 'Europe/London'
7
- TIME_ZONE_DATA_SOURCE = u'/usr/share/zoneinfo/'
5
+ import six
8
6
9
7
10
8
class TimezoneError (Exception ):
11
9
pass
12
10
13
11
14
- class tzfile (dateutil .tz .tzfile ):
15
-
16
- def _find_ttinfo (self , dtm , laststd = 0 ):
17
- """Faster version of parent class's _find_ttinfo() as this uses bisect rather than a linear search."""
18
- if dtm is None :
19
- # This will happen, for example, when a datetime.time object gets utcoffset() called.
20
- raise ValueError ('tzinfo object can not calculate offset for date %s' % dtm )
21
- ts = ((dtm .toordinal () - dateutil .tz .EPOCHORDINAL ) * 86400
22
- + dtm .hour * 3600
23
- + dtm .minute * 60
24
- + dtm .second )
25
- idx = bisect .bisect_right (self ._trans_list , ts )
26
- if len (self ._trans_list ) == 0 or idx == len (self ._trans_list ):
27
- return self ._ttinfo_std
28
- if idx == 0 :
29
- return self ._ttinfo_before
30
- if laststd :
31
- while idx > 0 :
32
- tti = self ._trans_idx [idx - 1 ]
33
- if not tti .isdst :
34
- return tti
35
- idx -= 1
36
- else :
37
- return self ._ttinfo_std
38
- else :
39
- return self ._trans_idx [idx - 1 ]
40
-
41
-
42
12
def mktz (zone = None ):
43
13
"""
44
- Return a new timezone based on the zone using the python-dateutil
45
- package. This convenience method is useful for resolving the timezone
46
- names as dateutil.tz.tzfile requires the full path.
14
+ Return a new timezone (tzinfo object) based on the zone using the python-dateutil
15
+ package.
47
16
48
17
The concise name 'mktz' is for convenient when using it on the
49
18
console.
50
19
51
20
Parameters
52
21
----------
53
22
zone : `String`
54
- The zone for the timezone. This defaults to 'local'.
23
+ The zone for the timezone. This defaults to local, returning:
24
+ tzlocal.get_localzone()
55
25
56
26
Returns
57
27
-------
@@ -61,14 +31,17 @@ def mktz(zone=None):
61
31
- - - - - -
62
32
TimezoneError : Raised if a user inputs a bad timezone name.
63
33
"""
64
-
65
34
if zone is None :
66
- zone = DEFAULT_TIME_ZONE_NAME
67
- _path = os .path .join (TIME_ZONE_DATA_SOURCE , zone )
68
- try :
69
- tz = tzfile (_path )
70
- except (ValueError , IOError ) as err :
71
- raise TimezoneError ('Timezone "%s" can not be read, error: "%s"' % (zone , err ))
35
+ zone = tzlocal .get_localzone ().zone
36
+ zone = six .u (zone )
37
+ tz = dateutil .tz .gettz (zone )
38
+ if not tz :
39
+ raise TimezoneError ('Timezone "%s" can not be read' % (zone ))
72
40
# Stash the zone name as an attribute (as pytz does)
73
- tz .zone = zone if not zone .startswith (TIME_ZONE_DATA_SOURCE ) else zone [len (TIME_ZONE_DATA_SOURCE ):]
41
+ if not hasattr (tz , 'zone' ):
42
+ tz .zone = zone
43
+ for p in dateutil .tz .TZPATHS :
44
+ if zone .startswith (p ):
45
+ tz .zone = zone [len (p ) + 1 :]
46
+ break
74
47
return tz
0 commit comments