How to use utcoffset method in freezegun

Best Python code snippet using freezegun

tzinfo.py

Source:tzinfo.py Github

copy

Full Screen

...59 '''60 def fromutc(self, dt):61 '''See datetime.tzinfo.fromutc'''62 return (dt + self._utcoffset).replace(tzinfo=self)63 def utcoffset(self,dt):64 '''See datetime.tzinfo.utcoffset'''65 return self._utcoffset66 def dst(self,dt):67 '''See datetime.tzinfo.dst'''68 return _notime69 def tzname(self,dt):70 '''See datetime.tzinfo.tzname'''71 return self._tzname72 def localize(self, dt, is_dst=False):73 '''Convert naive time to local time'''74 if dt.tzinfo is not None:75 raise ValueError, 'Not naive datetime (tzinfo is already set)'76 return dt.replace(tzinfo=self)77 def normalize(self, dt, is_dst=False):78 '''Correct the timezone information on the given datetime'''79 if dt.tzinfo is None:80 raise ValueError, 'Naive time - no tzinfo set'81 return dt.replace(tzinfo=self)82 def __repr__(self):83 return '<StaticTzInfo %r>' % (self.zone,)84 def __reduce__(self):85 # Special pickle to zone remains a singleton and to cope with86 # database changes.87 return pytz._p, (self.zone,)88class DstTzInfo(BaseTzInfo):89 '''A timezone that has a variable offset from UTC90 The offset might change if daylight savings time comes into effect,91 or at a point in history when the region decides to change their92 timezone definition.93 '''94 # Overridden in subclass95 _utc_transition_times = None # Sorted list of DST transition times in UTC96 _transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding97 # to _utc_transition_times entries98 zone = None99 # Set in __init__100 _tzinfos = None101 _dst = None # DST offset102 def __init__(self, _inf=None, _tzinfos=None):103 if _inf:104 self._tzinfos = _tzinfos105 self._utcoffset, self._dst, self._tzname = _inf106 else:107 _tzinfos = {}108 self._tzinfos = _tzinfos109 self._utcoffset, self._dst, self._tzname = self._transition_info[0]110 _tzinfos[self._transition_info[0]] = self111 for inf in self._transition_info[1:]:112 if inf not in _tzinfos:113 _tzinfos[inf] = self.__class__(inf, _tzinfos)114 def fromutc(self, dt):115 '''See datetime.tzinfo.fromutc'''116 dt = dt.replace(tzinfo=None)117 idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)118 inf = self._transition_info[idx]119 return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf])120 def normalize(self, dt):121 '''Correct the timezone information on the given datetime122 If date arithmetic crosses DST boundaries, the tzinfo123 is not magically adjusted. This method normalizes the124 tzinfo to the correct one.125 To test, first we need to do some setup126 >>> from pytz import timezone127 >>> utc = timezone('UTC')128 >>> eastern = timezone('US/Eastern')129 >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'130 We next create a datetime right on an end-of-DST transition point,131 the instant when the wallclocks are wound back one hour.132 >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)133 >>> loc_dt = utc_dt.astimezone(eastern)134 >>> loc_dt.strftime(fmt)135 '2002-10-27 01:00:00 EST (-0500)'136 Now, if we subtract a few minutes from it, note that the timezone137 information has not changed.138 >>> before = loc_dt - timedelta(minutes=10)139 >>> before.strftime(fmt)140 '2002-10-27 00:50:00 EST (-0500)'141 But we can fix that by calling the normalize method142 >>> before = eastern.normalize(before)143 >>> before.strftime(fmt)144 '2002-10-27 01:50:00 EDT (-0400)'145 '''146 if dt.tzinfo is None:147 raise ValueError, 'Naive time - no tzinfo set'148 # Convert dt in localtime to UTC149 offset = dt.tzinfo._utcoffset150 dt = dt.replace(tzinfo=None)151 dt = dt - offset152 # convert it back, and return it153 return self.fromutc(dt)154 def localize(self, dt, is_dst=False):155 '''Convert naive time to local time.156 This method should be used to construct localtimes, rather157 than passing a tzinfo argument to a datetime constructor.158 is_dst is used to determine the correct timezone in the ambigous159 period at the end of daylight savings time.160 >>> from pytz import timezone161 >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'162 >>> amdam = timezone('Europe/Amsterdam')163 >>> dt = datetime(2004, 10, 31, 2, 0, 0)164 >>> loc_dt1 = amdam.localize(dt, is_dst=True)165 >>> loc_dt2 = amdam.localize(dt, is_dst=False)166 >>> loc_dt1.strftime(fmt)167 '2004-10-31 02:00:00 CEST (+0200)'168 >>> loc_dt2.strftime(fmt)169 '2004-10-31 02:00:00 CET (+0100)'170 >>> str(loc_dt2 - loc_dt1)171 '1:00:00'172 Use is_dst=None to raise an AmbiguousTimeError for ambiguous173 times at the end of daylight savings174 >>> try:175 ... loc_dt1 = amdam.localize(dt, is_dst=None)176 ... except AmbiguousTimeError:177 ... print 'Oops'178 Oops179 >>> loc_dt1 = amdam.localize(dt, is_dst=None)180 Traceback (most recent call last):181 [...]182 AmbiguousTimeError: 2004-10-31 02:00:00183 is_dst defaults to False184 >>> amdam.localize(dt) == amdam.localize(dt, False)185 True186 '''187 if dt.tzinfo is not None:188 raise ValueError, 'Not naive datetime (tzinfo is already set)'189 # Find the possibly correct timezones. We probably just have one,190 # but we might end up with two if we are in the end-of-DST191 # transition period. Or possibly more in some particularly confused192 # location...193 possible_loc_dt = set()194 for tzinfo in self._tzinfos.values():195 loc_dt = tzinfo.normalize(dt.replace(tzinfo=tzinfo))196 if loc_dt.replace(tzinfo=None) == dt:197 possible_loc_dt.add(loc_dt)198 if len(possible_loc_dt) == 1:199 return possible_loc_dt.pop()200 # If told to be strict, raise an exception since we have an201 # ambiguous case202 if is_dst is None:203 raise AmbiguousTimeError(dt)204 # Filter out the possiblilities that don't match the requested205 # is_dst206 filtered_possible_loc_dt = [207 p for p in possible_loc_dt208 if bool(p.tzinfo._dst) == is_dst209 ]210 # Hopefully we only have one possibility left. Return it.211 if len(filtered_possible_loc_dt) == 1:212 return filtered_possible_loc_dt[0]213 if len(filtered_possible_loc_dt) == 0:214 filtered_possible_loc_dt = list(possible_loc_dt)215 # If we get this far, we have in a wierd timezone transition216 # where the clocks have been wound back but is_dst is the same217 # in both (eg. Europe/Warsaw 1915 when they switched to CET).218 # At this point, we just have to guess unless we allow more219 # hints to be passed in (such as the UTC offset or abbreviation),220 # but that is just getting silly.221 #222 # Choose the earliest (by UTC) applicable timezone.223 def mycmp(a,b):224 return cmp(225 a.replace(tzinfo=None) - a.tzinfo._utcoffset,226 b.replace(tzinfo=None) - b.tzinfo._utcoffset,227 )228 filtered_possible_loc_dt.sort(mycmp)229 return filtered_possible_loc_dt[0]230 def utcoffset(self, dt):231 '''See datetime.tzinfo.utcoffset'''232 return self._utcoffset233 def dst(self, dt):234 '''See datetime.tzinfo.dst'''235 return self._dst236 def tzname(self, dt):237 '''See datetime.tzinfo.tzname'''238 return self._tzname239 def __repr__(self):240 if self._dst:241 dst = 'DST'242 else:243 dst = 'STD'244 if self._utcoffset > _notime:...

Full Screen

Full Screen

test_utcoffset.py

Source:test_utcoffset.py Github

copy

Full Screen

...32 tzinfoobject = UTCOffset(minutes=240)33 # This would raise ISOFormatError or a TypeError if dst info is invalid34 result = datetime.datetime.now(tzinfoobject)35 # Hacky way to make sure the tzinfo is what we'd expect...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run freezegun automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful