【问题标题】:How to convert the time of a datetime object to an integer?如何将 datetime 对象的时间转换为整数?
【发布时间】:2020-04-02 20:48:49
【问题描述】:

我需要两点之间的时间作为整数,来计算物体的速度。我的第一个想法是使用 datetime 对象,但我无法将它从 string 转换为 int:

from datetime import datetime


#this is already the right format in HH:MM:SS:MS 

d = (datetime.now()).time().isoformat() 
coverted = int(d) # not working because of the ":"

我已经在这里找到了解决方案(见下文),但如果我打印代码,我只会得到一个奇怪的数字,这对我没有任何帮助。

import time
from datetime import datetime
timestamp = int(time.mktime(datetime.now().timetuple())

【问题讨论】:

  • 请提供一个minimal reproducible example,包括您根据自己的研究和示例输入和输出尝试过的代码
  • 那个整数意味着什么或描述什么?
  • “对你毫无帮助的奇怪数字”是自 1.1.1970 以来的秒数
  • @DeepSpace 我需要两点之间的时间为整数,来计算物体的速度
  • @AlfredWächter timestamp 已经为您提供了以秒为单位的时间,timestamp2 - timestamp1 也是如此。不要发明一种处理时间的新方法,因为你失败(时区、闰年、其他与时间有关的有趣的恶作剧)。

标签: python datetime integer seconds


【解决方案1】:

首先使用您的日期格式并剪切您要查找的字符串:(使用Sub-String

d = (datetime.now()).time().isoformat()   
min = d[3:-10]
seconds = d[6:-7]
milliseconds = d[9:]

现在您可以对字符串使用int() 命令将它们转换为整数。 例如:

min = int(min)
print min+1

将打印当前分钟加一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多