本文整理汇总了Python中datetime.datetime.fromisoformat方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.fromisoformat方法的具体用法?Python datetime.fromisoformat怎么用?Python datetime.fromisoformat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.datetime
的用法示例。
在下文中一共展示了datetime.fromisoformat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_or_add_item
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def update_or_add_item(repo_items, commit_hash, item, definition, commit_timestamps,
equal_fn, type_ctor):
# If we've seen this item before, check previous definitions
if item in repo_items:
prev_defns = repo_items[item][HISTORY_KEY]
max_defn_i = max(range(len(prev_defns)),
key=lambda i: datetime.fromisoformat(prev_defns[i][DATES_KEY]["last"]))
max_defn = prev_defns[max_defn_i]
# If equal to previous commit, update date and commit on existing definition
if equal_fn(definition, max_defn):
new_defn = make_item_defn(max_defn, commit_hash, commit_timestamps)
repo_items[item][HISTORY_KEY][max_defn_i] = new_defn
# Otherwise, prepend changed definition for existing item
else:
new_defn = make_item_defn(definition, commit_hash, commit_timestamps)
repo_items[item][HISTORY_KEY] = prev_defns + [new_defn]
# We haven't seen this item before, add it
else:
defn = make_item_defn(definition, commit_hash, commit_timestamps)
repo_items[item] = type_ctor(defn, item)
return repo_items
示例2: datetime_parser
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def datetime_parser(data: dict) -> dict:
"""
Convert ISO strings into datetime objects
"""
for key, val in data.items():
if isinstance(val, str):
if "+00:00" in val:
try:
data[key] = datetime.fromisoformat(val)
except ValueError:
pass
try:
data[key] = datetime.strptime(val, r"%Y-%m-%d")
except ValueError:
pass
return data
示例3: criar_no_pagseguro
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def criar_no_pagseguro(self) -> 'PlanoAutomaticoRecorrente':
"""
Cria um plano automático na conta do pagseguro
:return: código do plano criado
"""
headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/vnd.pagseguro.com.br.v3+json;charset=ISO-8859-1'
}
response = requests.post(self._config.construir_url('/pre-approvals/request'), json=self._main_data,
headers=headers)
codigo_data = response.json()
if codigo_data.get('error', False):
raise PagseguroException(codigo_data, response.status_code)
dt = datetime.fromisoformat(codigo_data['date']).astimezone(pytz.UTC)
return PlanoAutomaticoRecorrente(codigo_data['code'], dt)
示例4: test_dataframe_datetime_column
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def test_dataframe_datetime_column(self):
assert_arrow_table_equals(
dataframe_to_arrow_table(
pd.DataFrame(
{"A": ["2019-09-17T21:21:00.123456Z", None]}, dtype="datetime64[ns]"
),
[Column("A", ColumnType.DATETIME())],
self.path,
),
arrow_table(
{
"A": pyarrow.array(
[dt.fromisoformat("2019-09-17T21:21:00.123456"), None],
type=pyarrow.timestamp(unit="ns", tz=None),
)
},
[atypes.Column("A", atypes.ColumnType.Datetime())],
),
)
示例5: test_arrow_datetime_column
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def test_arrow_datetime_column(self):
dataframe, columns = arrow_table_to_dataframe(
arrow_table(
{
"A": pyarrow.array(
[dt.fromisoformat("2019-09-17T21:21:00.123456"), None],
type=pyarrow.timestamp(unit="ns", tz=None),
)
},
[atypes.Column("A", atypes.ColumnType.Datetime())],
)
)
assert_frame_equal(
dataframe,
pd.DataFrame(
{"A": ["2019-09-17T21:21:00.123456Z", None]}, dtype="datetime64[ns]"
),
)
self.assertEqual(columns, [Column("A", ColumnType.DATETIME())])
示例6: fetch_data
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def fetch_data(category, type):
try:
response = requests.get('https://api.fitbit.com/1/user/-/' + category + '/' + type + '/date/today/1d.json',
headers={'Authorization': 'Bearer ' + FITBIT_ACCESS_TOKEN, 'Accept-Language': FITBIT_LANGUAGE})
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print("HTTP request failed: %s" % (err))
sys.exit()
data = response.json()
print("Got " + type + " from Fitbit")
for day in data[category.replace('/', '-') + '-' + type]:
points.append({
"measurement": type,
"time": LOCAL_TIMEZONE.localize(datetime.fromisoformat(day['dateTime'])).astimezone(pytz.utc).isoformat(),
"fields": {
"value": float(day['value'])
}
})
示例7: process_levels
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def process_levels(levels):
for level in levels:
type = level['level']
if type == "asleep":
type = "light"
if type == "restless":
type = "rem"
if type == "awake":
type = "wake"
time = datetime.fromisoformat(level['dateTime'])
utc_time = LOCAL_TIMEZONE.localize(time).astimezone(pytz.utc).isoformat()
points.append({
"measurement": "sleep_levels",
"time": utc_time,
"fields": {
"seconds": int(level['seconds'])
}
})
示例8: inspect_running_containers
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def inspect_running_containers() -> datetime:
log.info("Inspecting running containers.")
last_event_time = datetime.utcnow()
containers = cfg.client.containers.list(ignore_removed=True, sparse=True)
for container in containers:
container_id = container.id
data = cfg.client.api.inspect_container(container_id)
last_event_time = max(
last_event_time,
# not sure why mypy doesn't know about this method:
datetime.fromisoformat(data['State']['StartedAt'][:26]), # type: ignore
)
process_started_container_labels(
container_id, paused=container.status == 'paused'
)
log.debug('Finished inspection of running containers.')
return last_event_time
示例9: parse_date
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def parse_date(str_date):
try:
return datetime.fromisoformat(str_date)
except Exception:
formats = ('%Y-%m-%dT%H:%M:%S.%f%z',
'%Y-%m-%dT%H:%M:%S.%f',
'%Y-%m-%dT%H:%M:%S',
'%Y-%m-%dT%H:%M',
'%Y-%m-%d %H:%M:%S.%f%z',
'%Y-%m-%d %H:%M:%S.%f',
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M',
'%Y-%m-%d',)
for format in formats:
with ignored(ValueError):
return datetime.strptime(str_date, format)
raise ValueError('Date format is unknown')
示例10: _parse_datetime
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def _parse_datetime(value: str) -> datetime:
try:
return datetime.fromisoformat(value)
except ValueError:
return parse_date(value)
示例11: fromisoformat
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def fromisoformat(iso):
""" for python versions < 3.7 get datetime from isoformat """
d, t = iso.split('T')
year, month, day = d.split('-')
hours, minutes, seconds = t.split(':')
seconds = float(seconds[0:-1])
sec = int(seconds)
microseconds = int((seconds-sec)*1e6)
return datetime(int(year), int(month), int(day), int(hours), int(minutes), sec, microseconds)
示例12: _create_tuple_datetime
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def _create_tuple_datetime(name, time):
nt = namedtuple(name, ('utc', 'local', 'str'))
if not time:
return nt(utc=None, local=None, str='')
try:
utc = datetime.fromisoformat(time)
except AttributeError:
utc = fromisoformat(time)
utc = utc.replace(tzinfo=tz.tzutc())
local = utc.astimezone(tz.tzlocal())
string = local.isoformat()
return nt(utc=utc, local=local, str=string)
示例13: _defcon_action
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def _defcon_action(self, ctx: Context, days: int, action: Action) -> None:
"""Providing a structured way to do an defcon action."""
try:
response = await self.bot.api_client.get('bot/bot-settings/defcon')
data = response['data']
if "enable_date" in data and action is Action.DISABLED:
enabled = datetime.fromisoformat(data["enable_date"])
delta = datetime.now() - enabled
self.bot.stats.timing("defcon.enabled", delta)
except Exception:
pass
error = None
try:
await self.bot.api_client.put(
'bot/bot-settings/defcon',
json={
'name': 'defcon',
'data': {
# TODO: retrieve old days count
'days': days,
'enabled': action is not Action.DISABLED,
'enable_date': datetime.now().isoformat()
}
}
)
except Exception as err:
log.exception("Unable to update DEFCON settings.")
error = err
finally:
await ctx.send(self.build_defcon_msg(action, error))
await self.send_defcon_log(action, ctx.author, error)
self.bot.stats.gauge("defcon.threshold", days)
示例14: retrieve_files
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def retrieve_files(repo_info, cache_dir):
results = defaultdict(list)
timestamps = dict()
base_path = os.path.join(cache_dir, repo_info.name)
min_date = None
if repo_info.name in MIN_DATES:
min_date = utc_timestamp(datetime.fromisoformat(MIN_DATES[repo_info.name]))
if os.path.exists(repo_info.name):
shutil.rmtree(repo_info.name)
repo = Repo.clone_from(repo_info.url, repo_info.name)
repo.git.checkout(repo_info.branch)
try:
for rel_path in repo_info.get_change_files():
hashes = get_commits(repo, rel_path)
for _hash, (ts, index) in hashes.items():
if (min_date and ts < min_date):
continue
disk_path = os.path.join(base_path, _hash, rel_path)
if not os.path.exists(disk_path):
contents = get_file_at_hash(repo, _hash, rel_path)
dir = os.path.split(disk_path)[0]
if not os.path.exists(dir):
os.makedirs(dir)
with open(disk_path, 'wb') as f:
f.write(contents.encode("UTF-8"))
results[_hash].append(disk_path)
timestamps[_hash] = (ts, index)
except Exception:
# without this, the error will be silently discarded
raise
finally:
shutil.rmtree(repo_info.name)
return timestamps, results
示例15: __init__
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def __init__(self):
"""Initializer."""
if Config.MASU_DATE_OVERRIDE and Config.DEBUG and DateAccessor.mock_date_time is None:
# python-dateutil is needed in Python <=3.6.x;
# in Python 3.7 there is datetime.fromisoformat()
DateAccessor.mock_date_time = parser.parse(Config.MASU_DATE_OVERRIDE)
if DateAccessor.mock_date_time.tzinfo is None:
DateAccessor.mock_date_time = DateAccessor.mock_date_time.replace(tzinfo=pytz.UTC)
LOG.info("Initializing masu date/time to %s", str(DateAccessor.mock_date_time))