Python pytz.UTC Examples
The following are 30
code examples of pytz.UTC().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pytz
, or try the search function
.
Example #1
Source File: base.py From darksky with MIT License | 7 votes |
def __init__(self, **params): try: timezone = pytz.timezone(params.pop('timezone', None)) except (pytz.UnknownTimeZoneError, AttributeError): timezone = pytz.UTC for field in self.__annotations__: api_field = undo_snake_case_key(field) if self.__annotations__[field] == datetime: params[api_field] = get_datetime_from_unix( params.get(api_field), timezone ) if api_field in params: setattr(self, field, params.get(api_field)) else: setattr(self, field, None)
Example #2
Source File: test_timezones.py From recruit with Apache License 2.0 | 6 votes |
def test_frame_align_aware(self): idx1 = date_range('2001', periods=5, freq='H', tz='US/Eastern') idx2 = date_range('2001', periods=5, freq='2H', tz='US/Eastern') df1 = DataFrame(np.random.randn(len(idx1), 3), idx1) df2 = DataFrame(np.random.randn(len(idx2), 3), idx2) new1, new2 = df1.align(df2) assert df1.index.tz == new1.index.tz assert df2.index.tz == new2.index.tz # different timezones convert to UTC # frame with frame df1_central = df1.tz_convert('US/Central') new1, new2 = df1.align(df1_central) assert new1.index.tz == pytz.UTC assert new2.index.tz == pytz.UTC # frame with Series new1, new2 = df1.align(df1_central[0], axis=0) assert new1.index.tz == pytz.UTC assert new2.index.tz == pytz.UTC df1[0].align(df1_central, axis=0) assert new1.index.tz == pytz.UTC assert new2.index.tz == pytz.UTC
Example #3
Source File: taxii2.py From minemeld-core with Apache License 2.0 | 6 votes |
def _manage_time(self, now): last_run = self.last_taxii2_run if last_run: last_run = dt_to_millisec(datetime.strptime(self.last_taxii2_run, '%Y-%m-%dT%H:%M:%S.%fZ')) max_back = now - (self.initial_interval * 1000) if last_run is None or last_run < max_back: last_run = max_back begin = datetime.utcfromtimestamp(last_run / 1000) begin = begin.replace(tzinfo=pytz.UTC) end = datetime.utcfromtimestamp(now / 1000) end = end.replace(tzinfo=pytz.UTC) if self.lower_timestamp_precision: end = end.replace(second=0, microsecond=0) begin = begin.replace(second=0, microsecond=0) return begin, end
Example #4
Source File: utils.py From zun with Apache License 2.0 | 6 votes |
def zservice_get_data(**kwargs): """Simulate what the RPC layer will get from DB """ faketime = datetime.datetime(2001, 1, 1, tzinfo=pytz.UTC) return { 'binary': kwargs.get('binary', 'fake-binary'), 'host': kwargs.get('host', 'fake-host'), 'id': kwargs.get('id', 13), 'report_count': kwargs.get('report_count', 13), 'disabled': kwargs.get('disabled', False), 'disabled_reason': kwargs.get('disabled_reason'), 'forced_down': kwargs.get('forced_down', False), 'last_seen_up': kwargs.get('last_seen_up', faketime), 'created_at': kwargs.get('created_at', faketime), 'updated_at': kwargs.get('updated_at', faketime), 'availability_zone': kwargs.get('availability_zone', 'fake-zone'), }
Example #5
Source File: find_clips.py From lrrbot with Apache License 2.0 | 6 votes |
def check_deleted_clips(period, slugs): """ Go through any clips we have in the DB that weren't returned from the Twitch query, and check if they actually exist (maybe they dropped out of the "last day" early) or if they've been deleted, in which case mark that in the DB. """ period = datetime.timedelta(days={'day': 1, 'week': 7, 'month': 28}[period]) start = datetime.datetime.now(pytz.UTC) - period with engine.begin() as conn: clips = conn.execute(sqlalchemy.select([TBL_CLIPS.c.id, TBL_CLIPS.c.slug]) .where(TBL_CLIPS.c.time >= start) .where(TBL_CLIPS.c.slug.notin_(slugs)) .where(TBL_CLIPS.c.deleted == False)) for clipid, slug in clips: if get_clip_info(slug, check_missing=True) is None: conn.execute(TBL_CLIPS.update().values(deleted=True).where(TBL_CLIPS.c.id == clipid))
Example #6
Source File: test_serializers.py From figures with MIT License | 6 votes |
def setup(self, db): self.a_datetime = datetime.datetime(2018, 2, 2, tzinfo=pytz.UTC) self.user_attributes = { 'username': 'alpha_one', 'email': 'alpha_one@example.com', 'profile__name': 'Alpha One', 'profile__country': 'CA', 'profile__gender': 'o', 'date_joined': self.a_datetime, 'profile__year_of_birth': 1989, 'profile__level_of_education': 'other', } self.user = UserFactory(**self.user_attributes) self.serializer = GeneralUserDataSerializer(instance=self.user) self.expected_fields = [ 'id', 'username', 'email', 'fullname','country', 'is_active', 'gender', 'date_joined', 'year_of_birth', 'level_of_education', 'courses', 'language_proficiencies', ]
Example #7
Source File: date_accessor.py From koku with GNU Affero General Public License v3.0 | 6 votes |
def today(self): """ Return the current date and time. When the environment variable MASU_DEBUG is set to True, the MASU_DATE_OVERRIDE environment variable can be used to override masu's current date and time. Args: (None) Returns: (datetime.datetime): Current datetime object example: 2018-07-24 15:47:33 """ current_date = datetime.now(tz=pytz.UTC) if Config.DEBUG and DateAccessor.mock_date_time: seconds_delta = current_date - DateAccessor.date_time_last_accessed DateAccessor.date_time_last_accessed = current_date DateAccessor.mock_date_time = DateAccessor.mock_date_time + seconds_delta current_date = DateAccessor.mock_date_time return current_date
Example #8
Source File: test_timestamp.py From recruit with Apache License 2.0 | 6 votes |
def test_nanosecond_string_parsing(self): ts = Timestamp('2013-05-01 07:15:45.123456789') # GH 7878 expected_repr = '2013-05-01 07:15:45.123456789' expected_value = 1367392545123456789 assert ts.value == expected_value assert expected_repr in repr(ts) ts = Timestamp('2013-05-01 07:15:45.123456789+09:00', tz='Asia/Tokyo') assert ts.value == expected_value - 9 * 3600 * 1000000000 assert expected_repr in repr(ts) ts = Timestamp('2013-05-01 07:15:45.123456789', tz='UTC') assert ts.value == expected_value assert expected_repr in repr(ts) ts = Timestamp('2013-05-01 07:15:45.123456789', tz='US/Eastern') assert ts.value == expected_value + 4 * 3600 * 1000000000 assert expected_repr in repr(ts) # GH 10041 ts = Timestamp('20130501T071545.123456789') assert ts.value == expected_value assert expected_repr in repr(ts)
Example #9
Source File: test_timestamp.py From recruit with Apache License 2.0 | 6 votes |
def test_class_ops_pytz(self): def compare(x, y): assert (int(Timestamp(x).value / 1e9) == int(Timestamp(y).value / 1e9)) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(timezone('UTC'))) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
Example #10
Source File: app_filters.py From yata with GNU General Public License v3.0 | 6 votes |
def ts2date(timestamp, fmt=None): import datetime import pytz if not timestamp: return "N/A" try: d = datetime.datetime.fromtimestamp(int(timestamp), tz=pytz.UTC) except BaseException: d = datetime.datetime.fromtimestamp(0, tz=pytz.UTC) # return "{:04d}/{:02d}/{:02d} {:02d}:{:02d}".format(d.year, d.month, d.day, d.hour, d.minute) if fmt is None: # return d.strftime("%Y/%m/%d %I:%M %p") return d.strftime("%Y/%m/%d %H:%M") else: return d.strftime(fmt)
Example #11
Source File: test_timestamp.py From recruit with Apache License 2.0 | 6 votes |
def test_class_ops_dateutil(self): def compare(x, y): assert (int(np.round(Timestamp(x).value / 1e9)) == int(np.round(Timestamp(y).value / 1e9))) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(tzutc())) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
Example #12
Source File: invoice_ex.py From Automate-it with MIT License | 5 votes |
def get_payments(user_id, month): tz = [ x for x in users if x["id"] == user_id] tot_payment = 0.00 for p in payments: dt = datetime.strptime(p["created_at"], '%Y-%m-%dT%H:%M:%S.%fZ') dt = dt.replace(tzinfo=pytz.UTC) dt = dt.astimezone(timezone(tz[0]["timezone"])) if p["id"] == user_id and dt.month == month: tot_payment += p["amount"] return tot_payment #Get platform usage for user based on user_id and month
Example #13
Source File: test_date_accessor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_today_with_timezone_string(self): """Test that a timezone string works as expected.""" string_tz = "UTC" current_utc_time = datetime.utcnow() accessor = DateAccessor() result_time = accessor.today_with_timezone(string_tz) self.assertEqual(current_utc_time.date(), result_time.date()) self.assertEqual(current_utc_time.hour, result_time.hour) self.assertEqual(current_utc_time.minute, result_time.minute) self.assertEqual(result_time.tzinfo, pytz.UTC)
Example #14
Source File: date_accessor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def today_with_timezone(self, timezone): """Return the current datetime at the timezone indictated. When the environment variable MASU_DEBUG is set to True, the MASU_DATE_OVERRIDE environment variable can be used to override masu's current date and time. Args: timezone (str/datetime.tzinfo) Either a valid timezone string or an instance or subclass of datetime.tzinfo. examples: 'US/Eastern', pytz.UTC Returns: (datetime.datetime): Current datetime object example: 2018-07-24 15:47:33 """ if isinstance(timezone, str): try: timezone = pytz.timezone(timezone) except pytz.exceptions.UnknownTimeZoneError as err: LOG.error(err) raise DateAccessorError(err) elif not isinstance(timezone, tzinfo): err = "timezone must be a valid timezone string or subclass of datetime.tzinfo" raise DateAccessorError(err) current_date = datetime.now(tz=timezone) if Config.DEBUG and DateAccessor.mock_date_time: seconds_delta = current_date - DateAccessor.date_time_last_accessed DateAccessor.date_time_last_accessed = current_date DateAccessor.mock_date_time = DateAccessor.mock_date_time + seconds_delta current_date = DateAccessor.mock_date_time return current_date
Example #15
Source File: handy.py From yata with GNU General Public License v3.0 | 5 votes |
def timestampToDate(timestamp, fmt=False): import datetime import pytz d = datetime.datetime.fromtimestamp(timestamp, tz=pytz.UTC) if fmt is False: return d elif type(fmt) == bool and fmt: return d.strftime("%Y/%m/%d %H:%M TCT") else: return d.strftime(fmt)
Example #16
Source File: tap_mongodb.py From pipelinewise with Apache License 2.0 | 5 votes |
def _serialize_datetime(val): """ Serialize Bson and python datetime types Args: val: datetime value Returns: serialized datetime value """ if isinstance(val, bson.datetime.datetime): timezone = tzlocal.get_localzone() try: local_datetime = timezone.localize(val) utc_datetime = local_datetime.astimezone(pytz.UTC) except Exception as ex: if str(ex) == 'year is out of range' and val.year == 0: # NB: Since datetimes are persisted as strings, it doesn't # make sense to blow up on invalid Python datetimes (e.g., # year=0). In this case we're formatting it as a string and # passing it along down the pipeline. return '{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}.{:06d}Z'.format(val.year, val.month, val.day, val.hour, val.minute, val.second, val.microsecond) raise MongoDBInvalidDatetimeError('Found invalid datetime {}'.format(val)) return singer_strftime(utc_datetime) if isinstance(val, datetime.datetime): timezone = tzlocal.get_localzone() local_datetime = timezone.localize(val) utc_datetime = local_datetime.astimezone(pytz.UTC) return singer_strftime(utc_datetime) return None
Example #17
Source File: test_date_accessor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_today_override_override_not_set(self): """Test today() with override set when debug is true.""" Config.DEBUG = True Config.MASU_DATE_OVERRIDE = None accessor = DateAccessor() today = accessor.today() expected_date = datetime.now(tz=pytz.UTC) self.assertEqual(today.year, expected_date.year) self.assertEqual(today.month, expected_date.month) self.assertEqual(today.day, expected_date.day) self.assertEqual(today.tzinfo, pytz.UTC)
Example #18
Source File: test_date_accessor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_today_override_debug_false(self): """Test today() with override when debug is false.""" fake_tz = pytz.timezone(self.fake.timezone()) fake_dt = self.fake.date_time(tzinfo=fake_tz) Config.DEBUG = False Config.MASU_DATE_OVERRIDE = fake_dt accessor = DateAccessor() today = accessor.today() expected_date = datetime.now(tz=pytz.UTC) self.assertEqual(today.year, expected_date.year) self.assertEqual(today.month, expected_date.month) self.assertEqual(today.day, expected_date.day) self.assertEqual(today.tzinfo, pytz.UTC)
Example #19
Source File: test_date_accessor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_today_override(self): """Test today() with override.""" fake_dt = self.fake.date_time(tzinfo=pytz.UTC) Config.DEBUG = True Config.MASU_DATE_OVERRIDE = fake_dt.strftime("%Y-%m-%d %H:%M:%S") accessor = DateAccessor() today = accessor.today() self.assertEqual(today.year, fake_dt.year) self.assertEqual(today.month, fake_dt.month) self.assertEqual(today.day, fake_dt.day) self.assertEqual(today.tzinfo.tzname(today), str(pytz.UTC))
Example #20
Source File: test_date_accessor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_today_override_override_not_set_debug_false(self): """Test today() with override not set when debug is false.""" Config.DEBUG = False Config.MASU_DATE_OVERRIDE = None accessor = DateAccessor() today = accessor.today() expected_date = datetime.now(tz=pytz.UTC) self.assertEqual(today.year, expected_date.year) self.assertEqual(today.month, expected_date.month) self.assertEqual(today.day, expected_date.day) self.assertEqual(today.tzinfo, pytz.UTC)
Example #21
Source File: anomali.py From minemeld-core with Apache License 2.0 | 5 votes |
def _calc_age_out(self, indicator, attributes): etsattribute = self.prefix+'_expiration_ts' if etsattribute in attributes: original_ets = attributes[etsattribute] LOG.debug('%s - original_ets: %s', self.name, original_ets) original_ets = original_ets[:19] ets = datetime.datetime.strptime( original_ets, '%Y-%m-%dT%H:%M:%S' ).replace(tzinfo=pytz.UTC) LOG.debug('%s - expiration_ts set for %s', self.name, indicator) return dt_to_millisec(ets) return super(Intelligence, self)._calc_age_out(indicator, attributes)
Example #22
Source File: invoice_ex.py From Automate-it with MIT License | 5 votes |
def get_usage(user_id, month): tz = [ x for x in users if x["id"] == user_id] tot_usage = 0.00 for u in usage: dt = datetime.strptime(u["created_at"], '%Y-%m-%dT%H:%M:%S.%fZ') dt = dt.replace(tzinfo=pytz.UTC) dt = dt.astimezone(timezone(tz[0]["timezone"])) if u["id"] == user_id and dt.month == month: tot_usage += u["charge"] return tot_usage #Generate invoice template in HTML
Example #23
Source File: test_ace_api.py From ACE with Apache License 2.0 | 5 votes |
def test_submit_with_utc_timezone(self): # make sure we can submit with a UTC timezone already set result = self._submit(event_time=self._get_localized_submit_time()) self.assertIsNotNone(result) self.assertTrue('result' in result) result = result['result'] self.assertIsNotNone(result['uuid']) uuid = result['uuid'] root = RootAnalysis(storage_dir=workload_storage_dir(uuid)) root.load() self.assertEquals(root.event_time, self._get_localized_submit_time())
Example #24
Source File: test_ace_api.py From ACE with Apache License 2.0 | 5 votes |
def _get_localized_submit_time(self): return ace_api.LOCAL_TIMEZONE.localize(self._get_submit_time()).astimezone(pytz.UTC)
Example #25
Source File: mlbsession.py From mlbv with GNU General Public License v3.0 | 5 votes |
def get_access_token(self): if not self._state["access_token"] or not self._state["access_token_expiry"] or \ self.access_token_expiry < datetime.datetime.now(tz=pytz.UTC): try: self.update_api_keys() except requests.exceptions.HTTPError: # Clear token and then try to get a new access_token self.update_api_keys() LOG.debug("access_token: %s" %(self._state["access_token"])) return self._state["access_token"], self._state["access_token_expiry"]
Example #26
Source File: api_v2.py From lrrbot with Apache License 2.0 | 5 votes |
def get_clips(session): days = float(flask.request.values.get('days', 14)) startdt = datetime.datetime.now(pytz.UTC) - datetime.timedelta(days=days) full = int(flask.request.values.get('full', 0)) clips = server.db.metadata.tables["clips"] with server.db.engine.begin() as conn: if full: clipdata = conn.execute(sqlalchemy.select( [clips.c.slug, clips.c.title, clips.c.vodid, clips.c.rating]) .where(clips.c.time >= startdt) .where(clips.c.deleted == False) .order_by(clips.c.time.asc())).fetchall() clipdata = [ { 'slug': slug, 'title': title, 'vodid': vodid, 'rating': rating, 'url': CLIP_URL.format(slug), } for slug, title, vodid, rating in clipdata ] return flask.jsonify(clipdata) else: clipdata = conn.execute(sqlalchemy.select([clips.c.slug]) .where(clips.c.rating == True) .where(clips.c.time >= startdt) .where(clips.c.deleted == False) .order_by(clips.c.time.asc())).fetchall() clipdata = "\n".join(CLIP_URL.format(slug) for slug, in clipdata) return flask.wrappers.Response(clipdata, mimetype="text/plain")
Example #27
Source File: test_timestamp.py From recruit with Apache License 2.0 | 5 votes |
def test_constructor_invalid_tz(self): # GH#17690 with pytest.raises(TypeError, match='must be a datetime.tzinfo'): Timestamp('2017-10-22', tzinfo='US/Eastern') with pytest.raises(ValueError, match='at most one of'): Timestamp('2017-10-22', tzinfo=utc, tz='UTC') with pytest.raises(ValueError, match="Invalid frequency:"): # GH#5168 # case where user tries to pass tz as an arg, not kwarg, gets # interpreted as a `freq` Timestamp('2012-01-01', 'US/Pacific')
Example #28
Source File: api.py From lrrbot with Apache License 2.0 | 5 votes |
def get_clips(session): if not session['user']['is_mod']: return flask.jsonify(status="ERR") days = float(flask.request.values.get('days', 14)) startdt = datetime.datetime.now(pytz.UTC) - datetime.timedelta(days=days) full = int(flask.request.values.get('full', 0)) clips = server.db.metadata.tables["clips"] with server.db.engine.begin() as conn: if full: clipdata = conn.execute(sqlalchemy.select( [clips.c.slug, clips.c.title, clips.c.vodid, clips.c.rating]) .where(clips.c.time >= startdt) .where(clips.c.deleted == False) .order_by(clips.c.time.asc())).fetchall() clipdata = [ { 'slug': slug, 'title': title, 'vodid': vodid, 'rating': rating, 'url': CLIP_URL.format(slug), } for slug, title, vodid, rating in clipdata ] return flask.jsonify(clipdata) else: clipdata = conn.execute(sqlalchemy.select([clips.c.slug]) .where(clips.c.rating == True) .where(clips.c.time >= startdt) .where(clips.c.deleted == False) .order_by(clips.c.time.asc())).fetchall() clipdata = "\n".join(CLIP_URL.format(slug) for slug, in clipdata) return flask.wrappers.Response(clipdata, mimetype="text/plain")
Example #29
Source File: test_timestamp.py From recruit with Apache License 2.0 | 5 votes |
def test_constructor_tz_or_tzinfo(self): # GH#17943, GH#17690, GH#5168 stamps = [Timestamp(year=2017, month=10, day=22, tz='UTC'), Timestamp(year=2017, month=10, day=22, tzinfo=utc), Timestamp(year=2017, month=10, day=22, tz=utc), Timestamp(datetime(2017, 10, 22), tzinfo=utc), Timestamp(datetime(2017, 10, 22), tz='UTC'), Timestamp(datetime(2017, 10, 22), tz=utc)] assert all(ts == stamps[0] for ts in stamps)
Example #30
Source File: tasks.py From contratospr-api with Apache License 2.0 | 5 votes |
def parse_date(value): if not value: return None ms = int(re.search(r"\d+", value).group()) return datetime.datetime.utcfromtimestamp(ms // 1000).replace(tzinfo=pytz.UTC)