def get_requested_time_hr(self):
return datetime.fromtimestamp(self.requested_time).replace(tzinfo=tz.tzlocal()).hour
python类tzlocal()的实例源码
def get_requested_time_hr(self):
return datetime.fromtimestamp(self.requested_time).replace(tzinfo=tz.tzlocal()).hour
def pretty_print_datetime(dt):
# Make sure the `dt` is timezone aware before pretty printing.
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
dt_pretty = dt.replace(tzinfo=tz.gettz('UTC'))
dt_pretty = dt_pretty.astimezone(tz.tzlocal())
else:
dt_pretty = dt.astimezone(tz.tzlocal())
dt_pretty_friendly = dt_pretty.strftime('%a %d %b, %I:%M%p')
dt_pretty_humanized = humanize.naturaltime(dt_pretty.replace(tzinfo=None))
return '%s (%s)' % (dt_pretty_friendly, dt_pretty_humanized,)
def testEquality(self):
tz1 = tz.tzlocal()
tz2 = tz.tzlocal()
# Explicitly calling == and != here to ensure the operators work
self.assertTrue(tz1 == tz2)
self.assertFalse(tz1 != tz2)
def testInequalityFixedOffset(self):
tzl = tz.tzlocal()
tzos = tz.tzoffset('LST', total_seconds(tzl._std_offset))
tzod = tz.tzoffset('LDT', total_seconds(tzl._std_offset))
self.assertFalse(tzl == tzos)
self.assertFalse(tzl == tzod)
self.assertTrue(tzl != tzos)
self.assertTrue(tzl != tzod)
def testInequalityInvalid(self):
tzl = tz.tzlocal()
UTC = tz.tzutc()
self.assertTrue(tzl != 1)
self.assertTrue(tzl != tz.tzutc())
self.assertFalse(tzl == 1)
self.assertFalse(tzl == UTC)
def testInequalityUnsupported(self):
tzl = tz.tzlocal()
self.assertTrue(tzl == ComparesEqual)
self.assertFalse(tzl != ComparesEqual)
def gettz(self, tzname):
# Actual time zone changes are handled by the _gettz_context function
return tz.tzlocal()
def _testTzFunc(self, tzval, func, std_val, dst_val):
"""
This generates tests about how the behavior of a function ``func``
changes between STD and DST (e.g. utcoffset, tzname, dst).
It assume that DST starts the 2nd Sunday in March and ends the 1st
Sunday in November
"""
with TZEnvContext(tzval):
dt1 = datetime(2015, 2, 1, 12, 0, tzinfo=tz.tzlocal()) # STD
dt2 = datetime(2015, 5, 1, 12, 0, tzinfo=tz.tzlocal()) # DST
self.assertEqual(func(dt1), std_val)
self.assertEqual(func(dt2), dst_val)
def testTimeOnlyOffsetLocalUTC(self):
with TZEnvContext(self.UTC):
self.assertEqual(dt_time(13, 20, tzinfo=tz.tzlocal()).utcoffset(),
timedelta(0))
def testTimeOnlyOffsetLocalDST(self):
with TZEnvContext(self.TZ_EST):
self.assertIs(dt_time(13, 20, tzinfo=tz.tzlocal()).utcoffset(),
None)
def testTimeOnlyDSTLocalUTC(self):
with TZEnvContext(self.UTC):
self.assertEqual(dt_time(13, 20, tzinfo=tz.tzlocal()).dst(),
timedelta(0))
def testPickleTzLocal(self):
self.assertPicklable(tz.tzlocal())
def parse_timestamp(value):
"""Parse a timestamp into a datetime object.
Supported formats:
* iso8601
* rfc822
* epoch (value is an integer)
This will return a ``datetime.datetime`` object.
"""
if isinstance(value, (int, float)):
# Possibly an epoch time.
return datetime.datetime.fromtimestamp(value, tzlocal())
else:
try:
return datetime.datetime.fromtimestamp(float(value), tzlocal())
except (TypeError, ValueError):
pass
try:
# In certain cases, a timestamp marked with GMT can be parsed into a
# different time zone, so here we provide a context which will
# enforce that GMT == UTC.
return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})
except (TypeError, ValueError) as e:
raise ValueError('Invalid timestamp "%s": %s' % (value, e))
def _local_now():
return datetime.datetime.now(tzlocal())
def _is_expired(self, credentials):
end_time = parse(credentials['Credentials']['Expiration'])
now = datetime.datetime.now(tzlocal())
seconds = total_seconds(end_time - now)
return seconds < self.EXPIRY_WINDOW_SECONDS
def testCreateFromEgtWithAttributes(self):
"""
Test creation of new taskwarrior tasks with attributes from a project file
"""
datedata = datetime.datetime(2031, 1, 2, 0, 0, tzinfo=tzlocal())
test_attributes = [("due", "2031-01-02", datedata),
("wait", "2031-01-02", datedata),
("start", "2031-01-02", datedata),
("end", "2031-01-02", datedata),
("until", "2031-01-02", datedata),
("scheduled", "2031-01-02", datedata),
("priority", "H", "H"),
("due", "2030-12-26+week", datedata),
]
for key, value, data in test_attributes:
attr = "{}:{}".format(key, value)
with self.subTest(config=attr):
self.write_project([
"body line1",
"t new test task "+attr,
"body line3",
])
proj = Project(self.projectfile, statedir=self.workdir.name)
proj.body.force_load_tw(config_filename=self.taskrc)
proj.load()
task = proj.body.tasks[0]
self.assertIsNone(task.task)
self.assertTrue(task.is_new)
self.assertIsNone(task.id)
self.assertEqual(task.desc, "new test task")
self.assertEqual(task.attributes, {key: value})
proj.body.sync_tasks()
self.assertIsNotNone(task.task)
self.assertFalse(task.is_new)
self.assertIsNotNone(task.id)
self.assertEqual(task.task["description"], "new test task")
self.assertEqual(task.task[key], data)
def _list_single_object(self, s3_path):
# When we know we're dealing with a single object, we can avoid
# a ListObjects operation (which causes concern for anyone setting
# IAM policies with the smallest set of permissions needed) and
# instead use a HeadObject request.
if self.operation_name == 'delete':
# If the operation is just a single remote delete, there is
# no need to run HeadObject on the S3 object as none of the
# information gained from HeadObject is required to delete the
# object.
return s3_path, {'Size': None, 'LastModified': None}
bucket, key = find_bucket_key(s3_path)
try:
params = {'Bucket': bucket, 'Key': key}
params.update(self.request_parameters.get('HeadObject', {}))
response = self._client.head_object(**params)
except ClientError as e:
# We want to try to give a more helpful error message.
# This is what the customer is going to see so we want to
# give as much detail as we have.
if not e.response['Error']['Code'] == '404':
raise
# The key does not exist so we'll raise a more specific
# error message here.
response = e.response.copy()
response['Error']['Message'] = 'Key "%s" does not exist' % key
raise ClientError(response, 'HeadObject')
response['Size'] = int(response.pop('ContentLength'))
last_update = parse(response['LastModified'])
response['LastModified'] = last_update.astimezone(tzlocal())
return s3_path, response
def _make_last_mod_str(self, last_mod):
"""
This function creates the last modified time string whenever objects
or buckets are being listed
"""
last_mod = parse(last_mod)
last_mod = last_mod.astimezone(tzlocal())
last_mod_tup = (str(last_mod.year), str(last_mod.month).zfill(2),
str(last_mod.day).zfill(2),
str(last_mod.hour).zfill(2),
str(last_mod.minute).zfill(2),
str(last_mod.second).zfill(2))
last_mod_str = "%s-%s-%s %s:%s:%s" % last_mod_tup
return last_mod_str.ljust(19, ' ')
def _date_parser(date_string):
return parse(date_string).astimezone(tzlocal())