【问题标题】:Unconverted Data Remains after Format格式化后保留未转换的数据
【发布时间】:2018-09-15 11:20:03
【问题描述】:

我已经查看了与 strptime 和未转换的数据剩余相关的其他问题,但很难找出我在代码中哪里出错了。

            currentTime = format(currentTime, '%H:%M:%S')
            #remove the current time from phone time
            timeDifferenceValue = datetime.datetime.strptime(str(currentTime), FMS) - datetime.datetime.strptime(
                str(ptime) + ":00", FMS)
            else:
                time_left = time_left[-7:]
                time_leftHatch = datetime.datetime.strptime(time_left, FMS) - timeDifferenceValue
                time_leftHatch = format(time_leftHatch, '%H:%M:%S')

在这个阶段发现了错误:

                                        time_leftHatch = datetime.datetime.strptime(time_left, FMS) - timeDifferenceValue

timeleft 和 timeDifference 的值分别是:

time_left = 1:29:47 timeDifferenceValue = 0:13:31

错误: 未转换的数据仍然存在::47

约翰在 cmets 中提到我应该更改删除不必要的 strptime 的过度使用。这似乎已经解决了未转换的数据剩余。

例如,timeDifferenceValue 已经是时间格式,所以根本不需要更改。

有什么想法吗?

【问题讨论】:

  • 您可以将代码简化为一个失败的strptime。请这样做,并发布输入字符串和格式字符串,不要有多余的其他代码。
  • 嗨,约翰,感谢您的评论。抱歉,我对 Python 还很陌生,但我不太清楚你把它变成一个单一的 strptime 是什么意思。代码中几乎所有的值实际上都是字符串(不包括我认为的字符串——我现在已经从中删除了 strptime)。通过删除这个 strptime,它似乎已经解决了这个问题。我不明白多么不幸,因为我认为它会由于 FMS 而转换。我现在会删除所有不必要的代码。再次感谢!

标签: python-3.x strptime


【解决方案1】:

当前的问题是:

datetime.datetime.strptime("0:"+str(time_left), FMS)

我不确定您为什么要在前面加上“0:”,但这会导致您的 strptime 格式仅解析前三个值的“0:1:29:47”。 “未转换的数据”错误让您知道输入字符串中存在格式字符串未处理的一些额外信息。

不过,更好的解决方法是停止字符串化和 strptiming,这将继续让您感到悲伤。您已经有了一些在代码中使用 timedelta 的提示。在 Python 中取时间差会返回一个 timedelta,将 timedelta 添加到 time 会返回一个新时间。这样做可以让您获得结构化数据和明确定义的结果。

例如,

# do this early, don't go back to string
phone_time = datetime.datetime.strptime(ptime + ':00', FMS)

# and leave this a datetime instead of stringifying it later
currentTime = datetime.datetime.now() + timedelta(hours=1)

# now you can just take the difference
timeDifferenceValue = currentTime - ptime

还有:

if str(timeDifferenceValue).__contains__("-"):

变成

if timeDifferenceValue < timedelta(0):

希望你能指出正确的方向!

【讨论】:

  • 嗨 Aron,非常感谢您的解释。您完全可以使用“0:”。我实际上最终删除了这个。最初之所以这样,是因为我使用的是AWS Image Recognition,它是从屏幕截图中提取手机时间,然后从当前时间中扣除。这意味着我必须在开头添加一个 0:。但是,这应该不再是问题,因为默认情况下,如果需要,它将转到 01:XX:XX。
  • 太棒了!我添加了更多关于 datetime 和 timedelta 的内容。希望有帮助。欢迎使用 Python!
猜你喜欢
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多