def get_date_from_buildid(bid):
"""Get a date from buildid
Args:
bid (str): build_id
Returns:
date: date object
"""
# 20160407164938 == 2016 04 07 16 49 38
bid = str(bid)
year = int(bid[:4])
month = int(bid[4:6])
day = int(bid[6:8])
hour = int(bid[8:10])
minute = int(bid[10:12])
second = int(bid[12:14])
return __pacific.localize(datetime(year, month, day, hour, minute, second)).astimezone(pytz.utc)
python类utc()的实例源码
def test_create(self, request):
resp = create_mock_json('tests/resources/task_router/activities_instance.json')
resp.status_code = 201
request.return_value = resp
activities = Activities(BASE_URI, AUTH)
activity = activities.create("Test Activity", True)
self.assertTrue(activity is not None)
self.assertEqual(activity.date_created, datetime(2014, 5, 14, 10, 50, 2, tzinfo=pytz.utc))
exp_params = {
'FriendlyName': "Test Activity",
'Available': "true"
}
request.assert_called_with("POST", "{0}/Activities".format(BASE_URI),
data=exp_params, auth=AUTH,
use_json_extension=False)
def __init__(self, clip_id, project_id, rank, title, descr, clip_start_utc, url,
category=None, timecodes=None):
url_parts = url.split('_')
start_ts = url_parts[-2]
start_ts = datetime.strptime(start_ts, '%Y%m%d%H%M%S')
start_ts = start_ts.replace(tzinfo=pytz.utc)
duration = url_parts[-1].replace('.mp4', '')
duration = timedelta(hours=int(duration[0:2]), minutes=int(duration[2:4]), seconds=int(duration[4:6]))
super().__init__(clip_id, title, category, start_ts.isoformat(), (start_ts + duration).isoformat(), timecodes, url)
self.project_id = project_id
self.rank = rank
self.descr = descr
self.clip_start_utc = clip_start_utc
self.duration = duration
def parse_time_range_from_url(adaptive_url):
"""
Parse the time information available in a video URL.
:param adaptive_url: Video URL, which contains time info.
:return: Tuple of start time, end time, and duration
"""
filename = adaptive_url.split('/')[-1]
filename = filename.replace('.mp4', '')
find_part = '_pc_'
ts_part = filename[filename.find(find_part) + len(find_part):]
start_ts, duration = ts_part.split('_')
start_ts = datetime.strptime(start_ts, '%Y%m%d%H%M%S')
start_ts = start_ts.replace(tzinfo=pytz.utc)
duration = timedelta(hours=int(duration[:2]), minutes=int(duration[2:4]), seconds=int(duration[4:]))
end_ts = start_ts + duration
return start_ts, end_ts, duration
def _generate_cached_enrollments(user, program, num_course_runs=1, data=None):
"""
Helper method to generate CachedEnrollments for test cases
"""
fake = faker.Factory.create()
course = CourseFactory.create(program=program)
course_run_params = dict(before_now=True, after_now=False, tzinfo=pytz.utc)
course_runs = [
CourseRunFactory.create(
course=course,
enrollment_start=fake.date_time_this_month(**course_run_params),
start_date=fake.date_time_this_month(**course_run_params),
enrollment_end=fake.date_time_this_month(**course_run_params),
end_date=fake.date_time_this_year(**course_run_params),
) for _ in range(num_course_runs)
]
factory_kwargs = dict(user=user)
if data is not None:
factory_kwargs['data'] = data
return [CachedEnrollmentFactory.create(course_run=course_run, **factory_kwargs) for course_run in course_runs]
def __init__(self, data_file='', reader=septo3d_reader, wind_screen=2,
temperature_screen=2,
localisation={'city': 'Montpellier', 'latitude': 43.61,
'longitude': 3.87},
timezone='UTC'):
self.data_path = data_file
self.models = {'global_radiation': PPFD_to_global,
'vapor_pressure': humidity_to_vapor_pressure,
'PPFD': global_to_PPFD,
'degree_days': linear_degree_days}
self.timezone = pytz.timezone(timezone)
if data_file is '':
self.data = None
else:
self.data = reader(data_file)
date = self.data['date']
date = map(lambda x: self.timezone.localize(x), date)
utc = map(lambda x: x.astimezone(pytz.utc), date)
self.data.index = utc
self.data.index.name = 'date_utc'
self.wind_screen = wind_screen
self.temperature_screen = temperature_screen
self.localisation = localisation
def test_success_datetime_from_timestamp(self, datetime_tuple, timestamp):
"""Test successful calls to datetime_from_timestamp()."""
if os.name == 'nt' and timestamp > TS_3001_LIMIT:
# Skip this test case, due to the lower limit on Windows
return
# Create the expected datetime result (always timezone-aware in UTC)
dt_unaware = datetime(*datetime_tuple)
exp_dt = pytz.utc.localize(dt_unaware)
# Execute the code to be tested
dt = datetime_from_timestamp(timestamp)
# Verify the result
assert dt == exp_dt
def test_time_function():
dt = datetime(1970, 1, 1)
timestamp = _datetime_to_utc_timestamp(dt)
assert timestamp == 0.0
assert type(timestamp) is float
assert time() != timestamp
with immobilus(dt):
assert time() == timestamp
assert time() != timestamp
with immobilus(dt.replace(tzinfo=pytz.utc)):
assert time() == timestamp
assert time() != timestamp
def test_create_notification(self, m):
register_uris({'account': ['create_notification']}, m)
subject = 'Subject'
notif_dict = {
'subject': subject,
'message': 'Message',
'start_at': '2015-04-01T00:00:00Z',
'end_at': '2018-04-01T00:00:00Z'
}
notif = self.account.create_notification(notif_dict)
self.assertIsInstance(notif, AccountNotification)
self.assertTrue(hasattr(notif, 'subject'))
self.assertEqual(notif.subject, subject)
self.assertTrue(hasattr(notif, 'start_at_date'))
self.assertIsInstance(notif.start_at_date, datetime.datetime)
self.assertEqual(notif.start_at_date.tzinfo, pytz.utc)
def set_timezone(self, timezone = None):
with self.tree_lock:
if isinstance(timezone, datetime.tzinfo):
self.timezone = timezone
else:
if timezone == None:
timezone = self.data_value(["timezone"], str, default='utc')
try:
oldtz = self.timezone
self.timezone = pytz.timezone(timezone)
except:
if isinstance(oldtz, datetime.tzinfo):
self.warn('Invalid timezone "%s" suplied. Falling back to the old timezone "%s"' \
% (timezone, oldtz.tzname), dtdata_defWarning, 2)
self.timezone = oldtz
else:
self.warn('Invalid timezone "%s" suplied. Falling back to UTC' % (timezone, ), dtdata_defWarning, 2)
self.timezone = pytz.utc
self.set_current_date()
self.set_current_weekdays()
def set_current_date(self, cdate = None):
with self.tree_lock:
if isinstance(cdate, datetime.datetime):
if cdate.tzinfo == None:
self.current_date = self.timezone.localize(cdate).date()
else:
self.current_date = self.timezone.normalize(cdate.astimezone(self.timezone)).date()
self.current_ordinal = self.current_date.toordinal()
elif isinstance(cdate, datetime.date):
self.current_date = cdate
self.current_ordinal = self.current_date.toordinal()
elif isinstance(cdate, int):
self.current_ordinal = cdate
datetime.datetime.fromordinal(cdate)
else:
if cdate != None:
self.warn('Invalid or no current_date "%s" suplied. Falling back to NOW' % (cdate, ), dtdata_defWarning, 2)
self.current_date = self.timezone.normalize(datetime.datetime.now(pytz.utc).astimezone(self.timezone)).date()
self.current_ordinal = self.current_date.toordinal()
def __init__(self, data_def, data = None, warnaction = "default", warngoal = sys.stderr, caller_id = 0):
self.tree_lock = RLock()
with self.tree_lock:
self.dtc = DataTreeConstants()
self.ddconv = DataDef_Convert(warnaction = warnaction , warngoal = warngoal, caller_id = caller_id)
self.caller_id = caller_id
self.print_tags = False
self.print_searchtree = False
self.show_result = False
self.fle = sys.stdout
if sys.modules['DataTreeGrab']._warnings == None:
sys.modules['DataTreeGrab']._warnings = _Warnings(warnaction, warngoal, caller_id)
else:
sys.modules['DataTreeGrab']._warnings.set_warnaction(warnaction, caller_id)
self.searchtree = None
self.timezone = pytz.utc
self.errorcode = dte.dtDataInvalid
self.result = []
self.data_def = None
self.init_data_def(data_def)
if data != None:
self.init_data(data)
def format_datetime(dttm):
# 1. Convert to timezone-aware
# 2. Convert to UTC
# 3. Format in ISO format
# 4. Add subsecond value if non-zero
# 5. Add "Z"
if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm) is None:
# dttm is timezone-naive; assume UTC
zoned = pytz.utc.localize(dttm)
else:
zoned = dttm.astimezone(pytz.utc)
ts = zoned.strftime("%Y-%m-%dT%H:%M:%S")
if zoned.microsecond > 0:
ms = zoned.strftime("%f")
ts = ts + '.' + ms.rstrip("0")
return ts + "Z"
def test_partial(self):
"""
You can use Filter macros to create partials from other Filter
types.
"""
MyDatetime = filter_macro(f.Datetime, timezone=12)
self.assertEqual(
MyDatetime().apply('2015-10-13 15:22:18'),
# By default, MyDatetime assumes a timezone of UTC+12...
datetime(2015, 10, 13, 3, 22, 18, tzinfo=utc),
)
self.assertEqual(
# ... however, we can override it.
MyDatetime(timezone=6).apply('2015-10-13 15:22:18'),
datetime(2015, 10, 13, 9, 22, 18, tzinfo=utc),
)
def test_pass_naive_timestamp_default_timezone(self):
"""
The incoming value is a naive timestamp, but the Filter is
configured not to treat naive timestamps as UTC.
"""
self.assertFilterPasses(
# The incoming value is a naive timestamp, and the Filter
# is configured to use UTC+8 by default.
self._filter(
'2015-05-12 09:20:03',
timezone = tzoffset('UTC+8', 8*3600),
),
# The resulting datetime is still converted to UTC.
datetime(2015, 5, 12, 1, 20, 3, tzinfo=utc),
)
def _ToTimeZone(t, tzinfo):
"""Converts 't' to the time zone 'tzinfo'.
Arguments:
t: a datetime object. It may be in any pytz time zone, or it may be
timezone-naive (interpreted as UTC).
tzinfo: a pytz timezone object, or None.
Returns:
a datetime object in the time zone 'tzinfo'
"""
if pytz is None:
return t.replace(tzinfo=None)
elif tzinfo:
if not t.tzinfo:
t = pytz.utc.localize(t)
return tzinfo.normalize(t.astimezone(tzinfo))
elif t.tzinfo:
return pytz.utc.normalize(t.astimezone(pytz.utc)).replace(tzinfo=None)
else:
return t
def convert_to_local_from_utc(utc_time):
local_timezone = tzlocal.get_localzone()
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
return local_time
def convert_to_tz_from_utc(utc_time, tz):
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(tz))
return local_time
def test_datetime_from_fields_correct(self):
el = {
"next_activity_date": "2017-03-20",
"next_activity_time": "14:01:02"
}
result = Organization.datetime_from_fields(el, 'next_activity_date', 'next_activity_time')
expected = datetime.datetime(2017, 3, 20, 14, 1, 2, 0, tzinfo=pytz.utc)
self.assertEquals(result, expected)
def test_datetime_from_simple_time_correct(self):
el = {u'update_time': u'2017-04-03 16:21:12'}
result = Organization.datetime_from_simple_time(el, u'update_time')
expected = datetime.datetime(2017, 4, 3, 16, 21, 12, 0, tzinfo=pytz.utc)
self.assertEquals(result, expected)