def test_timezone_dst(self): """ Test across DST transition, which technially is a timzone change. """ tz = pytz.timezone("US/Eastern") start = tz.localize(datetime(2020, 10, 30)) stop = tz.localize(datetime(2020, 11, 10)) res = list(croniter_range(start, stop, '0 0 * * *')) self.assertNotEqual(res[0].tzinfo, res[-1].tzinfo) self.assertEqual(len(res), 12)
def _detect_timezone_php(): tomatch = (time.tzname[0], time.timezone, time.daylight) now = datetime.datetime.now() matches = [] for tzname in pytz.all_timezones: try: tz = pytz.timezone(tzname) except IOError: continue try: indst = tz.localize(now).timetuple()[-1] if tomatch == (tz._tzname, -tz._utcoffset.seconds, indst): matches.append(tzname) # pylint: disable=pointless-except except AttributeError: pass if len(matches) > 1: warnings.warn( "We detected multiple matches for the timezone, choosing " "the first %s. (Matches where %s)" % (matches[0], matches)) if matches: return pytz.timezone(matches[0])
def test_yearlocator_pytz(): pytz = pytest.importorskip("pytz") tz = pytz.timezone('America/New_York') x = [ tz.localize(datetime.datetime(2010, 1, 1)) + datetime.timedelta(i) for i in range(2000) ] locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz) locator.create_dummy_axis() locator.set_view_interval( mdates.date2num(x[0]) - 1.0, mdates.date2num(x[-1]) + 1.0) t = np.array([ 733408.208333, 733773.208333, 734138.208333, 734503.208333, 734869.208333, 735234.208333, 735599.208333 ]) # convert to new epoch from old... t = t + mdates.date2num(np.datetime64('0000-12-31')) np.testing.assert_allclose(t, locator()) expected = [ '2009-01-01 00:00:00-05:00', '2010-01-01 00:00:00-05:00', '2011-01-01 00:00:00-05:00', '2012-01-01 00:00:00-05:00', '2013-01-01 00:00:00-05:00', '2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00' ] st = list(map(str, mdates.num2date(locator(), tz=tz))) assert st == expected
def _detect_timezone_php(): tomatch = (time.tzname[0], time.timezone, time.daylight) now = datetime.datetime.now() matches = [] for tzname in pytz.all_timezones: try: tz = pytz.timezone(tzname) except IOError: continue try: indst = tz.localize(now).timetuple()[-1] if tomatch == (tz._tzname, -tz._utcoffset.seconds, indst): matches.append(tzname) # pylint: disable-msg=W0704 except AttributeError: pass if len(matches) > 1: warnings.warn("We detected multiple matches for the timezone, choosing " "the first %s. (Matches where %s)" % (matches[0], matches)) if matches: return pytz.timezone(matches[0])
def set_tz(dt, tz): """Sets the timezone for a datetime object.""" if hasattr(tz, 'localize'): # works on pytz timezones # return tz.localize(dt, is_dst=None) # avoid crashing on datetimes with tzinfos return tz.localize(dt.replace(tzinfo=None), is_dst=None) return dt.replace(tzinfo=tz)
def testTimezoneSummerTime(self): tz = pytz.timezone('Europe/Athens') expected_schedule = [ (datetime(2013, 3, 31, 1, 30, 0), 7200), (datetime(2013, 3, 31, 2, 0, 0), 7200), (datetime(2013, 3, 31, 2, 30, 0), 7200), (datetime(2013, 3, 31, 4, 0, 0), 10800), (datetime(2013, 3, 31, 4, 30, 0), 10800), ] start = datetime(2013, 3, 31, 1, 0, 0) ct = croniter('*/30 * * * *', tz.localize(start)) self.assertScheduleTimezone(lambda: ct.get_next(datetime), expected_schedule) start = datetime(2013, 3, 31, 5, 0, 0) ct = croniter('*/30 * * * *', tz.localize(start)) self.assertScheduleTimezone(lambda: ct.get_prev(datetime), reversed(expected_schedule))
def test_std_dst3(self): """ DST tests This fixes https://github.com/taichino/croniter/issues/90 Adelaide, Australia: 15/04/2020 00:00 -> 15/03/2020 """ tz = pytz.timezone('Australia/Adelaide') schedule = croniter('0 0 24 * *', tz.localize(datetime(2020, 4, 15))) val1 = schedule.get_prev(datetime) dt1 = tz.localize(datetime(2020, 3, 24)) self.assertEqual(val1, dt1) val2 = schedule.get_next(datetime) dt2 = tz.localize(datetime(2020, 4, 24)) self.assertEqual(val2, dt2)
def days_in_year(self): """ Iterates over all the days in the given year, starting from 1.1. and ending in 31.12. """ tz = self.solarcalculator.timezone orig_date = self.solarcalculator.date one_day = timedelta(1,0) dt = tz.localize(datetime(orig_date.year, 1, 1, 12, 0, 0, 0)) while (dt.year == orig_date.year): yield dt # Increase by one day dt = dt + one_day
def test_localize(self): # Test some corner cases around DST tz = EWSTimeZone('Europe/Copenhagen') with warnings.catch_warnings(): # localize() is deprecated but we still want to test it. Silence the DeprecationWarning warnings.simplefilter("ignore") self.assertEqual( str( tz.localize(EWSDateTime(2023, 10, 29, 2, 36, 0), is_dst=False)), '2023-10-29 02:36:00+01:00') self.assertEqual( str( tz.localize(EWSDateTime(2023, 10, 29, 2, 36, 0), is_dst=None)), '2023-10-29 02:36:00+02:00') self.assertEqual( str( tz.localize(EWSDateTime(2023, 10, 29, 2, 36, 0), is_dst=True)), '2023-10-29 02:36:00+02:00') self.assertEqual( str( tz.localize(EWSDateTime(2023, 3, 26, 2, 36, 0), is_dst=False)), '2023-03-26 02:36:00+01:00') self.assertEqual( str( tz.localize(EWSDateTime(2023, 3, 26, 2, 36, 0), is_dst=None)), '2023-03-26 02:36:00+01:00') self.assertEqual( str( tz.localize(EWSDateTime(2023, 3, 26, 2, 36, 0), is_dst=True)), '2023-03-26 02:36:00+02:00')
def force_tz(obj, tz): """Converts a datetime to the given timezone. The tz argument can be an instance of tzinfo or a string such as 'Europe/London' that will be passed to pytz.timezone. Naive datetimes are forced to the timezone. Wise datetimes are converted. """ if not isinstance(tz, tzinfo): tz = pytz.timezone(tz) if (obj.tzinfo is None) or (obj.tzinfo.utcoffset(obj) is None): return tz.localize(obj) else: return obj.astimezone(tz)
def get_offset(self, dt): # get the appropriate UTC offset for the current time # this dependnds on whether we are in daylight savings time or not # returns True if date is in daylight savings in LA timezone # returns False otherwise tz = pytz.timezone('America/Los_Angeles') tz_aware = tz.localize(dt, is_dst=None) isdst = tz_aware.tzinfo._dst.seconds != 0 offset = -8 # set the UTC offset if isdst: offset = -7 return offset
def test_std_dst2(self): """ DST tests This fixes https://github.com/taichino/croniter/issues/87 São Paulo, Brazil: 18/02/2018 00:00 -> 17/02/2018 23:00 """ tz = pytz.timezone("America/Sao_Paulo") local_dates = [ # 17-22: 00 -> 18-00:00 (tz.localize(datetime(2018, 2, 17, 21, 0, 0)), '2018-02-18 00:00:00-03:00'), # 17-23: 00 -> 18-00:00 (tz.localize(datetime(2018, 2, 17, 22, 0, 0)), '2018-02-18 00:00:00-03:00'), # 17-23: 00 -> 18-00:00 (tz.localize(datetime(2018, 2, 17, 23, 0, 0)), '2018-02-18 00:00:00-03:00'), # 18-00: 00 -> 19-00:00 (tz.localize(datetime(2018, 2, 18, 0, 0, 0)), '2018-02-19 00:00:00-03:00'), # 17-22: 00 -> 18-00:00 (tz.localize(datetime(2018, 2, 17, 21, 5, 0)), '2018-02-18 00:00:00-03:00'), # 17-23: 00 -> 18-00:00 (tz.localize(datetime(2018, 2, 17, 22, 5, 0)), '2018-02-18 00:00:00-03:00'), # 17-23: 00 -> 18-00:00 (tz.localize(datetime(2018, 2, 17, 23, 5, 0)), '2018-02-18 00:00:00-03:00'), # 18-00: 00 -> 19-00:00 (tz.localize(datetime(2018, 2, 18, 0, 5, 0)), '2018-02-19 00:00:00-03:00'), ] ret1 = [ croniter("0 0 * * *", d[0]).get_next(datetime) for d in local_dates ] sret1 = ['{0}'.format(d) for d in ret1] lret1 = ['{0}'.format(d[1]) for d in local_dates] self.assertEqual(sret1, lret1)
def getTimeZoneOffset(value): if isinstance(value, str): try: tz = pytz.timezone(value) except: tz = pytz.timezone(getTimeZoneName(value)) else: tz = pytz.timezone(getTimeZoneName(value)) # compute the timezone's offset now = datetime.datetime.now() if tz: now1 = tz.localize(now) now2 = pytz.utc.localize(now) return RPNMeasurement((now2 - now1).total_seconds(), 'seconds') return RPNMeasurement(0, 'seconds')
def test_yearlocator_pytz(): import pytz tz = pytz.timezone('America/New_York') x = [tz.localize(datetime.datetime(2010, 1, 1)) + datetime.timedelta(i) for i in range(2000)] locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz) locator.create_dummy_axis() locator.set_view_interval(mdates.date2num(x[0])-1.0, mdates.date2num(x[-1])+1.0) np.testing.assert_allclose([733408.208333, 733773.208333, 734138.208333, 734503.208333, 734869.208333, 735234.208333, 735599.208333], locator()) expected = ['2009-01-01 00:00:00-05:00', '2010-01-01 00:00:00-05:00', '2011-01-01 00:00:00-05:00', '2012-01-01 00:00:00-05:00', '2013-01-01 00:00:00-05:00', '2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00'] st = list(map(str, mdates.num2date(locator(), tz=tz))) assert st == expected
def test_localize(self): # Test some cornercases around DST tz = EWSTimeZone('Europe/Copenhagen') self.assertEqual( str(tz.localize(EWSDateTime(2023, 10, 29, 2, 36, 0), is_dst=False)), '2023-10-29 02:36:00+01:00') self.assertEqual( str(tz.localize(EWSDateTime(2023, 10, 29, 2, 36, 0), is_dst=None)), '2023-10-29 02:36:00+02:00') self.assertEqual( str(tz.localize(EWSDateTime(2023, 10, 29, 2, 36, 0), is_dst=True)), '2023-10-29 02:36:00+02:00') self.assertEqual( str(tz.localize(EWSDateTime(2023, 3, 26, 2, 36, 0), is_dst=False)), '2023-03-26 02:36:00+01:00') self.assertEqual( str(tz.localize(EWSDateTime(2023, 3, 26, 2, 36, 0), is_dst=None)), '2023-03-26 02:36:00+01:00') self.assertEqual( str(tz.localize(EWSDateTime(2023, 3, 26, 2, 36, 0), is_dst=True)), '2023-03-26 02:36:00+02:00')
def localize(self, timezone, naive): tz = pytz.timezone(timezone) local = tz.localize(naive) return local
def localize(cls, timezone, naive): tz = pytz.timezone(timezone) local = tz.localize(naive) return local
def split_time_range_into_subranges_with_same_offset(time_zone, start, end, params={}): """Method which divides a range of local time into "constant-UTC-offset" subranges, such that each subrange can be passed as UTC (with the provided interval) to the Density API. The responses to these queries can then be merged to represent e.g. "daily intervals", even though the days of DST transitions are not the same length as other days. Args: - time_zone (str): local time zone - start (datetime): local start date - end (datetime): local end date Kwargs: - params ({interval, order}): Density API count endpoint params Returns: - [{start: end: gap:}] array of query-ready sub ranges """ tz = pytz.timezone(time_zone) # Convert start and end into UTC times start = tz.localize(start).astimezone(pytz.UTC) end = tz.localize(end).astimezone(pytz.UTC) results = [] # Same defaults as API params['interval'] = params.get('interval', '1h') params['order'] = params.get('order', 'asc') interval = parse_interval_as_timedelta(params['interval']) reverse = params['order'].lower() == 'desc' # Validate start and end timestamps if (start >= end): raise ValueError("Start must be before end!") # Create a list of DST transitions within this range of (local) time transitions = [] for i in range(len(tz._utc_transition_times)): time = pytz.UTC.localize(tz._utc_transition_times[i]) if start < time and time < end: shift = tz._transition_info[i - 1][0] - tz._transition_info[i][0] transitions.append({'time': time, 'shift': shift}) # Save the last segment and interval boundaries that we've processed so far last_segment = end if reverse else start last_interval = last_segment # Generate necessary segments to avoid each DST boundary while len(transitions) > 0: # Depending on the order of results, we pull from either end of the transitions array transition = transitions.pop() if reverse else transitions.pop(0) transition_point = transition['time'] transition_shift = transition['shift'] # Skip by "interval" in the correct order until we've either passed or reached the transition while last_interval > transition_point if reverse else last_interval < transition_point: last_interval = last_interval - interval if reverse else last_interval + interval # Create a subrange from the last segment to this transition, preserving "time forwards" order results.append({ 'start': transition_point if reverse else last_segment, 'end': last_segment if reverse else transition_point, 'gap': False }) # If querying days or weeks, shift the next interval to align with the new offset if params['interval'][-1] in ['d', 'w']: last_interval = last_interval - transition_shift if reverse else last_interval + transition_shift # If there is a gap before the next interval, it will need to be fetched separately if last_interval != transition_point: results.append({ 'start': last_interval if reverse else transition_point, 'end': transition_point if reverse else last_interval, 'gap': True }) # Continue from the last even interval last_segment = last_interval # Add the last interval if necessary if start < last_segment if reverse else end > last_segment: results.append({ 'start': start if reverse else last_segment, 'end': last_segment if reverse else end, 'gap': False }) # Return array of subranges return results
def get_target_info_pgne(self, in_time, in_tz): """ Combine event start, end, and baseline target Inputs: in_time: string cur_time in_tz: string timezone Returns: A dictionary of start, end datetime and baseline target """ target_info = [] event_info = self.get_event_info() _log.debug("TargetAgent: event info length is " + str(len(event_info.keys()))) if len(event_info.keys()) > 0: start = event_info['start'] end = event_info['end'] _log.debug('TargetAgent: EventInfo ' 'Start: {start} End: {end} '.format(start=start, end=end)) cur_time = parser.parse(in_time) if cur_time.tzinfo is None: tz = pytz.timezone(in_tz) cur_time = tz.localize(cur_time) # Convert to UTC before doing any processing start_utc = start.astimezone(pytz.utc) end_utc = end.astimezone(pytz.utc) cur_time_utc = cur_time.astimezone(pytz.utc) one_hour = timedelta(hours=1) start_utc_prev_hr = start_utc - one_hour end_utc_prev_hr = end_utc - one_hour # Use occupancy time if cont_after_dr is enabled if self.cont_after_dr == 'yes' and self.dr_mode != 'open_adr': end_utc_prev_hr = self.occ_time_utc - one_hour # Progress only if current hour is in range of one hour before start_time and one hour before end_time if start_utc_prev_hr <= cur_time_utc < end_utc_prev_hr: next_hour_utc = \ cur_time_utc.replace(minute=0, second=0, microsecond=0) + one_hour next_hour_end = next_hour_utc.replace(minute=59, second=59) # Decide cpb value cur_time_local = cur_time_utc.astimezone(self.local_tz) cbp_idx = cur_time_local.hour + 1 if cbp_idx >= len(self.cbps): cbp_idx = 0 cbps = self.cbps[cbp_idx] if cur_time_utc > end_utc: cbps = [0, 0, 0, 0] # Calculate baseline target baseline_targets = self.get_baseline_targets( cur_time_utc, start_utc, end_utc, cbps ) # Package output if baseline_targets is not None: #meta = {'type': 'float', 'tz': 'UTC', 'units': 'kW'} #time_meta = {'type': 'datetime', 'tz': 'UTC', 'units': 'datetime'} # target_info = [{ # "id": format_timestamp(next_hour_utc), # "start": format_timestamp(next_hour_utc), # "end": format_timestamp(next_hour_end), # "target": baseline_target, # "cbp": cbp # }, { # "id": time_meta, # "start": time_meta, # "end": time_meta, # "target": meta, # "cbp": meta # }] meta2 = {'type': 'string', 'tz': 'UTC', 'units': ''} delta = timedelta(minutes=0) for idx, cbp in enumerate(cbps): new_start = next_hour_utc + delta new_end = new_start + timedelta(minutes=14, seconds=59) new_target = baseline_targets[idx] target_info.append([{ "value": { "id": format_timestamp(new_start), "start": format_timestamp(new_start), "end": format_timestamp(new_end), "target": new_target, "cbp": cbp } }, { "value": meta2 }]) delta += timedelta(minutes=15) _log.debug( "TargetAgent: At time (UTC) {ts}" " TargetInfo is {ti}".format(ts=cur_time_utc, ti=target_info)) else: _log.debug('TargetAgent: Not in event time frame' ' {start} {cur} {end}'.format(start=start_utc_prev_hr, cur=cur_time_utc, end=end_utc_prev_hr)) return target_info
def get_target_info_wbe(self, in_time, in_tz): """ Combine event start, end, and baseline target Inputs: in_time: string cur_time in_tz: string timezone Returns: A dictionary of start, end datetime and baseline target """ target_info = [] event_info = self.get_event_info() _log.debug("TargetAgent: event info length is " + str(len(event_info.keys()))) if len(event_info.keys()) > 0: start = event_info['start'] end = event_info['end'] _log.debug('TargetAgent: EventInfo ' 'Start: {start} End: {end} '.format(start=start, end=end)) cur_time = parser.parse(in_time) if cur_time.tzinfo is None: tz = pytz.timezone(in_tz) cur_time = tz.localize(cur_time) # Convert to UTC before doing any processing start_utc = start.astimezone(pytz.utc) end_utc = end.astimezone(pytz.utc) cur_time_utc = cur_time.astimezone(pytz.utc) one_hour = timedelta(hours=1) start_utc_prev_hr = start_utc - one_hour end_utc_prev_hr = end_utc - one_hour # Use occupancy time if cont_after_dr is enabled if self.cont_after_dr == 'yes' and self.dr_mode != 'open_adr': end_utc_prev_hr = self.occ_time_utc - one_hour if start_utc_prev_hr <= cur_time_utc < end_utc_prev_hr: next_hour_utc = \ cur_time_utc.replace(minute=0, second=0, microsecond=0) + one_hour next_hour_end = next_hour_utc.replace(minute=59, second=59) # Decide cpb value cur_time_local = cur_time_utc.astimezone(self.local_tz) cbp_idx = cur_time_local.hour + 1 if cbp_idx >= len(self.cbps): cbp_idx = 0 cbps = self.cbps[cbp_idx] if cur_time_utc > end_utc: cbps = [0, 0, 0, 0] ####### Calculate baseline target baseline = [] with open(self.wbe_csv, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: wbe_ts = parser.parse(row[0]) if wbe_ts.year == cur_time_local.year \ and wbe_ts.month == cur_time_local.month \ and wbe_ts.day == cur_time_local.day: baseline = row[1:] break baseline = [float(i) for i in baseline] value = {} meta2 = {'type': 'string', 'tz': 'UTC', 'units': ''} for i in range(0, 24): ts = cur_time_local.replace(hour=i, minute=0, second=0) ts_epoch = mktime(ts.timetuple())*1000 value[ts_epoch] = baseline[i] baseline_msg = [{ "value": value }, { "value": meta2 }] headers = {'Date': format_timestamp(get_aware_utc_now())} target_topic = '/'.join(['analysis', 'PGnE', self.site, self.building, 'baseline']) self.vip.pubsub.publish( 'pubsub', target_topic, headers, baseline_msg).get(timeout=10) _log.debug("PGnE {topic}: {value}".format( topic=target_topic, value=baseline_msg)) meta = {'type': 'float', 'tz': self.tz, 'units': 'kW'} idx = cur_time_local.hour next_idx = idx+1 if next_idx >= len(baseline): next_idx = idx next_hr_baseline = baseline[next_idx] cur_idx = idx cur_hr_baseline = baseline[cur_idx] delta = (next_hr_baseline - cur_hr_baseline) / float(len(cbps)) baseline_targets = [] for index, cbp in enumerate(cbps): baseline_targets.append(cur_hr_baseline + index * delta - cbp) ######End target calculation # Package output if baseline_targets is not None: meta2 = {'type': 'string', 'tz': 'UTC', 'units': ''} delta = timedelta(minutes=0) for idx, cbp in enumerate(cbps): new_start = next_hour_utc + delta new_end = new_start + timedelta(minutes=14, seconds=59) new_target = baseline_targets[idx] target_info.append([{ "value": { "id": format_timestamp(new_start), "start": format_timestamp(new_start), "end": format_timestamp(new_end), "target": new_target, "cbp": cbp } }, { "value": meta2 }]) delta += timedelta(minutes=15) _log.debug( "TargetAgent: At time (UTC) {ts}" " TargetInfo is {ti}".format(ts=cur_time_utc, ti=target_info)) else: _log.debug('TargetAgent: Not in event time frame' ' {start} {cur} {end}'.format(start=start_utc_prev_hr, cur=cur_time_utc, end=end_utc_prev_hr)) return target_info
def to_naive_utc(self, datetime, tz_name): tz = tz_name and pytz.timezone(tz_name) or pytz.UTC return tz.localize(datetime.replace(tzinfo=None), is_dst=False).astimezone( pytz.UTC).replace(tzinfo=None)
# GH#13583 ts = Timestamp('2011-01-01', tz=dateutil.tz.tzlocal()) assert ts.tz == dateutil.tz.tzlocal() assert "tz='tzlocal()')" in repr(ts) tz = timezones.maybe_get_tz('tzlocal()') assert tz == dateutil.tz.tzlocal() # get offset using normal datetime for test offset = dateutil.tz.tzlocal().utcoffset(datetime(2011, 1, 1)) offset = offset.total_seconds() * 1000000000 assert ts.value + offset == Timestamp('2011-01-01').value @pytest.mark.parametrize('eastern, localize', [ (pytz.timezone('US/Eastern'), lambda tz, x: tz.localize(x)), (dateutil.tz.gettz('US/Eastern'), lambda tz, x: x.replace(tzinfo=tz))]) def test_infer_tz(eastern, localize): utc = pytz.utc start_naive = datetime(2001, 1, 1) end_naive = datetime(2009, 1, 1) start = localize(eastern, start_naive) end = localize(eastern, end_naive) assert (timezones.infer_tzinfo(start, end) is tslib._localize_pydatetime(start_naive, eastern).tzinfo) assert (timezones.infer_tzinfo(start, None) is tslib._localize_pydatetime(start_naive, eastern).tzinfo) assert (timezones.infer_tzinfo(None, end) is
def test_std_dst(self): """ DST tests This fixes https://github.com/taichino/croniter/issues/82 """ tz = pytz.timezone('Europe/Warsaw') # -> 2017-03-26 01:59+1:00 -> 03:00+2:00 local_date = tz.localize(datetime(2017, 3, 26)) val = croniter('0 0 * * *', local_date).get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 3, 27))) # local_date = tz.localize(datetime(2017, 3, 26, 1)) cr = croniter('0 * * * *', local_date) val = cr.get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 3, 26, 3))) val = cr.get_current(datetime) self.assertEqual(val, tz.localize(datetime(2017, 3, 26, 3))) # -> 2017-10-29 02:59+2:00 -> 02:00+1:00 local_date = tz.localize(datetime(2017, 10, 29)) val = croniter('0 0 * * *', local_date).get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 10, 30))) local_date = tz.localize(datetime(2017, 10, 29, 1, 59)) val = croniter('0 * * * *', local_date).get_next(datetime) self.assertEqual( val.replace(tzinfo=None), tz.localize(datetime(2017, 10, 29, 2)).replace(tzinfo=None)) local_date = tz.localize(datetime(2017, 10, 29, 2)) val = croniter('0 * * * *', local_date).get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 10, 29, 3))) local_date = tz.localize(datetime(2017, 10, 29, 3)) val = croniter('0 * * * *', local_date).get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 10, 29, 4))) local_date = tz.localize(datetime(2017, 10, 29, 4)) val = croniter('0 * * * *', local_date).get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 10, 29, 5))) local_date = tz.localize(datetime(2017, 10, 29, 5)) val = croniter('0 * * * *', local_date).get_next(datetime) self.assertEqual(val, tz.localize(datetime(2017, 10, 29, 6)))
def test_tzlocal_offset(): # see gh-13583 # # Get offset using normal datetime for test. ts = Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()) offset = dateutil.tz.tzlocal().utcoffset(datetime(2011, 1, 1)) offset = offset.total_seconds() * 1000000000 assert ts.value + offset == Timestamp("2011-01-01").value @pytest.fixture(params=[ (pytz.timezone("US/Eastern"), lambda tz, x: tz.localize(x)), (dateutil.tz.gettz("US/Eastern"), lambda tz, x: x.replace(tzinfo=tz)) ]) def infer_setup(request): eastern, localize = request.param start_naive = datetime(2001, 1, 1) end_naive = datetime(2009, 1, 1) start = localize(eastern, start_naive) end = localize(eastern, end_naive) return eastern, localize, start, end, start_naive, end_naive def test_infer_tz_compat(infer_setup):
def test_tzlocal_offset(): # see gh-13583 # # Get offset using normal datetime for test. ts = Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()) offset = dateutil.tz.tzlocal().utcoffset(datetime(2011, 1, 1)) offset = offset.total_seconds() * 1000000000 assert ts.value + offset == Timestamp("2011-01-01").value @pytest.fixture(params=[ (pytz.timezone("US/Eastern"), lambda tz, x: tz.localize(x)), (dateutil.tz.gettz("US/Eastern"), lambda tz, x: x.replace(tzinfo=tz)), ]) def infer_setup(request): eastern, localize = request.param start_naive = datetime(2001, 1, 1) end_naive = datetime(2009, 1, 1) start = localize(eastern, start_naive) end = localize(eastern, end_naive) return eastern, localize, start, end, start_naive, end_naive def test_infer_tz_compat(infer_setup):
def date_to_utc(date, timezone_str): """Converts date in timezone to utc""" tz = timezone(timezone_str) day = datetime(date.year, date.month, date.day) return tz.localize(day).astimezone(pytz.utc).replace(tzinfo=None)
ts = Timestamp('2011-01-01', tz=dateutil.tz.tzlocal()) assert ts.tz == dateutil.tz.tzlocal() assert "tz='tzlocal()')" in repr(ts) tz = timezones.maybe_get_tz('tzlocal()') assert tz == dateutil.tz.tzlocal() # get offset using normal datetime for test offset = dateutil.tz.tzlocal().utcoffset(datetime(2011, 1, 1)) offset = offset.total_seconds() * 1000000000 assert ts.value + offset == Timestamp('2011-01-01').value @pytest.mark.parametrize( 'eastern, localize', [(pytz.timezone('US/Eastern'), lambda tz, x: tz.localize(x)), (dateutil.tz.gettz('US/Eastern'), lambda tz, x: x.replace(tzinfo=tz))]) def test_infer_tz(eastern, localize): utc = pytz.utc start_naive = datetime(2001, 1, 1) end_naive = datetime(2009, 1, 1) start = localize(eastern, start_naive) end = localize(eastern, end_naive) assert (timezones.infer_tzinfo(start, end) is tslib._localize_pydatetime( start_naive, eastern).tzinfo) assert (timezones.infer_tzinfo(start, None) is tslib._localize_pydatetime( start_naive, eastern).tzinfo) assert (timezones.infer_tzinfo(None, end) is tslib._localize_pydatetime(