def validate(self, value, session=None):
if isinstance(value, (float, int)):
value = arrow.Arrow.fromtimestamp(value)
elif not isinstance(value, arrow.Arrow):
raise ValueError("Value must be timestamp or arrow.Arrow instance.")
return value
python类Arrow()的实例源码
def default(self, obj):
if isinstance(obj, arrow.Arrow):
return obj.format('YYYY-MM-DD HH:mm:ss ZZ')
elif isinstance(obj, object):
return 'cant_serialize_object'
return json.JSONEncoder.default(self, obj)
def check_processed_device(device):
keys = [
'model',
'name',
'serial',
'source',
'type',
'last_sync',
]
for key in keys:
assert key in device
assert isinstance(device['last_sync'], arrow.Arrow)
assert device['serial'] == '0xDECAFBAD'
assert device['source'] == 'landesk'
def json_serialize_datetime(obj):
"""Serialize a `datetime.datetime` or `arrow.Arrow` by converting to string in ISO format.
>>> import json
>>> json.dumps(arrow.get("2015-05-16 10:37"), default=json_serialize_datetime)
'"2015-05-16T10:37:00+00:00"'
>>> json.dumps(datetime.datetime.utcfromtimestamp(1431772620), default=json_serialize_datetime)
'"2015-05-16T10:37:00"'
"""
if isinstance(obj, (datetime.datetime, arrow.Arrow)):
return obj.isoformat(b'T' if six.PY2 else 'T')
raise TypeError("{!r} is not JSON serializable".format(obj))
def parse_parameters_list(dict_list):
"""
>>> import arrow
>>> returned = parse_parameters_list([
... { "name": "accounts:is_2sv_enrolled", "boolValue": False },
... { "name": "accounts:last_name", "stringValue": "Smith" },
... { "name": "accounts:drive_used_quota_in_mb", "intValue": "0" },
... { "name": "accounts:creation_time",
... "datetimeValue": "2010-10-28T10:26:35.000Z" },
... ])
>>> returned == {
... "accounts:is_2sv_enrolled": False,
... "accounts:last_name": "Smith",
... "accounts:drive_used_quota_in_mb": 0,
... "accounts:creation_time": arrow.Arrow(2010, 10, 28, 10, 26, 35),
... }
True
>>> parse_parameters_list([{ "name": "fakeValue", "otherType": False }])
Traceback (most recent call last):
...
ValueError: Failed to determine appropriate type for parameter 'fakeValue'
"""
retval = dict()
for item_dict in dict_list:
if 'boolValue' in item_dict:
value = item_dict['boolValue']
elif 'intValue' in item_dict:
value = int(item_dict['intValue'])
elif 'stringValue' in item_dict:
value = item_dict['stringValue']
elif 'datetimeValue' in item_dict:
value = arrow.get(item_dict['datetimeValue'])
else:
raise ValueError("Failed to determine appropriate type for parameter "
"{!r}".format(item_dict['name']))
retval[item_dict['name']] = value
return retval
def validate_arrow(value):
assert isinstance(
value, arrow.Arrow) or value is None, "Column only accepts arrow types, not {}".format(
type(value))
return value
def python_value(self, value):
"""Return the value in the data base as an arrow object.
Returns:
arrow.Arrow: An instance of arrow with the field filled in.
"""
value = super(ArrowDateTimeField, self).python_value(value)
if (isinstance(value, (datetime.datetime, datetime.date,
string_types))):
return arrow.get(value)
return value
def db_value(self, value):
"""Convert the Arrow instance to a datetime for saving in the db."""
if isinstance(value, string_types):
value = arrow.get(value)
if isinstance(value, arrow.Arrow):
value = value.datetime
return super(ArrowDateTimeField, self).db_value(value)
def default(self, obj):
if isinstance(obj, arrow.Arrow):
return obj.for_json()
elif isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(obj, datetime.date):
return obj.strftime('%Y-%m-%d')
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
def default(self, o):
if isinstance(o, arrow.Arrow):
return o.for_json()
else:
return super(self.__class__, self).default(o)
def utc_now():
"""
Return the utcnow arrow object
:return: Arrow
"""
return arrow.utcnow()
def get_action_time(time: str) -> arrow.Arrow:
time_str = time.strip().replace('at', '')
if time_str == "now":
return arrow.get(arrow.now(), tzinfo=tz.tzlocal())
else:
return arrow.get(
time_str,
'MMMM D, YYYY hh:mma',
tzinfo=tz.tzlocal())
def test_is_between(self):
self.assertEqual(ArrowUtil.is_between((10, 0), (20, 0), now=arrow.Arrow(2017, 8, 14, 12, 0)), True)
self.assertEqual(ArrowUtil.is_between((0, 0), (24, 0), now=arrow.Arrow(2017, 8, 14, 12, 0)), True)
self.assertEqual(ArrowUtil.is_between((10, 0), (24, 0), now=arrow.Arrow(2017, 8, 14, 9, 0)), False)
self.assertEqual(ArrowUtil.is_between((10, 0), (20, 0), now=arrow.Arrow(2017, 8, 14, 10, 0)), True)
self.assertEqual(ArrowUtil.is_between((10, 0), (20, 0), now=arrow.Arrow(2017, 8, 14, 20, 0)), True)
def test_get_curr_time_diff(self):
start = arrow.Arrow(2017, 8, 14, 12, 0)
end = arrow.Arrow(2017, 8, 14, 13, 0)
self.assertEqual(ArrowUtil.get_curr_time_diff(start=start, stop=end), 60)
self.assertEqual(ArrowUtil.get_curr_time_diff(start=start, stop=end, base_hour=True), 1)
def local_arrow(dt):
tz = get_current_request().weasyl_session.timezone
return arrow.Arrow.fromdatetime(tz.localtime(dt))
def convert_to_localtime(target):
tz = get_current_request().weasyl_session.timezone
if isinstance(target, arrow.Arrow):
return tz.localtime(target.datetime)
else:
target = int(get_time() if target is None else target) - _UNIXTIME_OFFSET
return tz.localtime_from_timestamp(target)
def age_in_years(birthdate):
"""
Determines an age in years based off of the given arrow.Arrow birthdate
and the current date.
"""
now = arrow.now()
is_upcoming = (now.month, now.day) < (birthdate.month, birthdate.day)
return now.year - birthdate.year - int(is_upcoming)
def iso8601(unixtime):
if isinstance(unixtime, arrow.Arrow):
return unixtime.isoformat().partition('.')[0] + 'Z'
else:
return datetime.datetime.utcfromtimestamp(unixtime - _UNIXTIME_OFFSET).isoformat() + 'Z'