【问题标题】:Python - for loop fails when passing datetime object back as a stringPython - 将日期时间对象作为字符串传回时,for循环失败
【发布时间】:2016-12-06 14:59:25
【问题描述】:

我对编码和 Python 非常陌生,我一直被这个 for 循环所困扰。基本上,对于每个 AWS 工作区(VDI 机器),我都在尝试返回工作区名称和上次登录的时间。使用“describe_workspaces_connection_status”可以轻松获得这些指标。

起初它失败了:

Calling DescribeWorkspaces()
Traceback (most recent call last):
File "./ws-conectionTS.py", line 20, in <module>
print "Workspace name " + item["WorkspaceId"] + " last connected on : " +   item["LastKnownUserConnectionTimestamp"]
TypeError: coercing to Unicode: need string or buffer, datetime.datetime found

经过一番谷歌搜索后,我意识到我需要将 datetime 对象作为字符串传递,因此添加了 str():

print "Workspace name " + item["WorkspaceId"] + " last connected on : " +  str(item["LastKnownUserConnectionTimestamp"])

现在,当我运行代码时,它会返回第一个工作区的数据,但随后会出错:

Calling DescribeWorkspaces()
Workspace name ws-qaazwssx last connected on : 2016-12-05  17:27:40.617000+00:00
Traceback (most recent call last):
File "./ws-conectionTS.py", line 20, in <module>
print "Workspace name " + item["WorkspaceId"] + " last connected on : " +  str(item["LastKnownUserConnectionTimestamp"])
KeyError: 'LastKnownUserConnectionTimestamp'

有人可以告诉我如何更改代码,以便它返回循环中每个项目的数据吗? 完整代码如下:

#!/usr/bin/python
import boto3
import datetime
import time

wsclient = boto3.client('workspaces')

nextToken = ""

while 1:

    if nextToken == "":
        print "Calling DescribeWorkspaces()"
        workspaces = wsclient.describe_workspaces_connection_status()
    else:
        print "Calling DescribeWorkspaces(NextToken=" + nextToken + ")"
        workspaces =      wsclient.describe_workspaces_connection_status(NextToken=nextToken)

    for item in workspaces["WorkspacesConnectionStatus"]:
        print "Workspace name " + item["WorkspaceId"] + " last connected on :   " + str(item["LastKnownUserConnectionTimestamp"])

    if workspaces.has_key("NextToken"):
    nextToken = workspaces["NextToken"]
    else:
        break

“describe_workspaces_connection_status”的响应是:

{
    'WorkspacesConnectionStatus': [
        {
            'WorkspaceId': 'string',
            'ConnectionState': 'CONNECTED'|'DISCONNECTED'|'UNKNOWN',
            'ConnectionStateCheckTimestamp': datetime(2015, 1, 1),
            'LastKnownUserConnectionTimestamp': datetime(2015, 1, 1)
        },
    ],
    'NextToken': 'string'
}

非常感谢!

【问题讨论】:

  • 看起来它在第一次迭代时工作正常,然后在第二次迭代中失败了。建议某些项目没有相同的现有密钥。不要访问像item["key"] 这样的项目,而是尝试使用item.get("key"),如果密钥不存在,它将返回None,或者item.get("key", "What I want if the key is not found")
  • 您发布的代码不是您正在运行的代码(if 后缺少缩进)。此外,如果我们知道 wsclient 或至少 workspacesitem 是什么,我们可以提供更好的帮助。
  • LastKnownUserConnectionTimestamp 在第二次尝试时似乎为空...您可以尝试在没有此字段的情况下运行代码来检查它吗?
  • @sytech - 完美的工作就像一个魅力:)
  • @hop - 这是我正在运行的代码。在这篇文章中格式化它时,我可能错过了缩进(放轻松,这是我的第一个 :))。前两个只是在用于进行 api 调用的代码中定义的变量。 'item' 是 for 循环中用于迭代结果的任意变量。

标签: python string datetime amazon-web-services


【解决方案1】:

感谢 sytech 的回答 - 工作代码:

#!/usr/bin/python
import boto3
import datetime
import time

wsclient = boto3.client('workspaces')

nextToken = ""

while 1:

    if nextToken == "":
        print "Calling DescribeWorkspaces()"
        workspaces = wsclient.describe_workspaces_connection_status()
    else:
        print "Calling DescribeWorkspaces(NextToken=" + nextToken + ")"
        workspaces =   wsclient.describe_workspaces_connection_status(NextToken=nextToken)

    for item in workspaces["WorkspacesConnectionStatus"]:
        print "Workspace name " + item["WorkspaceId"] + " last connected on : " + str(item.get("LastKnownUserConnectionTimestamp"))

    if workspaces.has_key("NextToken"):
        nextToken = workspaces["NextToken"]
    else:
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2011-10-18
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多