r''' Return a datetime.tzinfo implementation for the given timezone >>> from datetime import datetime, timedelta >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> timezone(unicode('US/Eastern')) is eastern True >>> utc_d
(zone)
| 128 | |
| 129 | |
| 130 | def timezone(zone): |
| 131 | r''' Return a datetime.tzinfo implementation for the given timezone |
| 132 | |
| 133 | >>> from datetime import datetime, timedelta |
| 134 | >>> utc = timezone('UTC') |
| 135 | >>> eastern = timezone('US/Eastern') |
| 136 | >>> eastern.zone |
| 137 | 'US/Eastern' |
| 138 | >>> timezone(unicode('US/Eastern')) is eastern |
| 139 | True |
| 140 | >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) |
| 141 | >>> loc_dt = utc_dt.astimezone(eastern) |
| 142 | >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' |
| 143 | >>> loc_dt.strftime(fmt) |
| 144 | '2002-10-27 01:00:00 EST (-0500)' |
| 145 | >>> (loc_dt - timedelta(minutes=10)).strftime(fmt) |
| 146 | '2002-10-27 00:50:00 EST (-0500)' |
| 147 | >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt) |
| 148 | '2002-10-27 01:50:00 EDT (-0400)' |
| 149 | >>> (loc_dt + timedelta(minutes=10)).strftime(fmt) |
| 150 | '2002-10-27 01:10:00 EST (-0500)' |
| 151 | |
| 152 | Raises UnknownTimeZoneError if passed an unknown zone. |
| 153 | |
| 154 | >>> try: |
| 155 | ... timezone('Asia/Shangri-La') |
| 156 | ... except UnknownTimeZoneError: |
| 157 | ... print('Unknown') |
| 158 | Unknown |
| 159 | |
| 160 | >>> try: |
| 161 | ... timezone(unicode('\N{TRADE MARK SIGN}')) |
| 162 | ... except UnknownTimeZoneError: |
| 163 | ... print('Unknown') |
| 164 | Unknown |
| 165 | |
| 166 | ''' |
| 167 | if zone is None: |
| 168 | raise UnknownTimeZoneError(None) |
| 169 | |
| 170 | if zone.upper() == 'UTC': |
| 171 | return utc |
| 172 | |
| 173 | try: |
| 174 | zone = ascii(zone) |
| 175 | except UnicodeEncodeError: |
| 176 | # All valid timezones are ASCII |
| 177 | raise UnknownTimeZoneError(zone) |
| 178 | |
| 179 | zone = _case_insensitive_zone_lookup(_unmunge_zone(zone)) |
| 180 | if zone not in _tzinfo_cache: |
| 181 | if zone in all_timezones_set: # noqa |
| 182 | fp = open_resource(zone) |
| 183 | try: |
| 184 | _tzinfo_cache[zone] = build_tzinfo(zone, fp) |
| 185 | finally: |
| 186 | fp.close() |
| 187 | else: |
nothing calls this directly
no test coverage detected