【问题标题】:find how much time is passed (datatime) between two rows找出两行之间经过了多少时间(日期时间)
【发布时间】:2020-08-15 11:23:18
【问题描述】:
Subject.iloc[1, 0]  is equal to 

datetime.time(13, 16, 14, 336000)

Subject.iloc[2, 0]  is equal to 

datetime.time(13, 16, 14, 338000)

我要做的就是找到从 Subject.iloc[1, 0] 到 Subject.iloc[2, 0] 的经过时间 .但是当我减去它们时,它会说

Subject.iloc[1, 0]-Subject.iloc[2, 0]
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

但后来我想也许我应该使用时间增量

  pd.to_timedelta(Subject.iloc[2, 0].astype(str))

说 AttributeError: 'datetime.time' 对象没有属性 'astype'

谁能帮我解决这个问题?我做错了什么?

这个

pd.to_timedelta(Subject.iloc[2, 0]) won't work

【问题讨论】:

  • 这是什么错误? pd.to_timedelta(Subject.iloc[2, 0])
  • @HenryHarutyunyan ValueError: Value must be Timedelta, string, integer, float, timedelta or convertible
  • pd.to_timedelta(str(Subject.iloc[2, 0]))?
  • @HenryHarutyunyan 是的!!!!谢谢!请在答案部分回答,以便我确认我的问题已解决。谢谢亨利!

标签: python pandas timestamp timedelta


【解决方案1】:

你可以试试这个

d1 = datetime.datetime.combine(datetime.date.today(), Subject.iloc[2, 0])
d2 = datetime.datetime.combine(datetime.date.today(), Subject.iloc[1, 0])
diff = d1 - d2

要使用 Pandas 的to_timedelta,请执行以下操作

pd.to_timedelta(str(Subject.iloc[2, 0]))

【讨论】:

  • 整栏怎么办? pd.to_timedelta(str(Subject['TIme'))?那是行不通的。你有什么想法吗?
  • 这会有帮助吗? kite.com/python/answers/…
  • 其实我想找出 Subject.iloc[0, 0] 与所有其他行之间的区别。如 Subject.iloc[2, 0]-Subject.iloc[0, 0]、Subject.iloc[3, 0]-Subject.iloc[0, 0] 等等。
  • @NavidRashedi idk 很多 Pandas,但我想你需要遍历所有行并减去 Subject.iloc[0, 0] 的固定值然后
【解决方案2】:

实际上,我最近不得不这样做。您可以将日期时间(或在我的情况下的时间结构对象)转换为“自纪元以来的秒数”,然后进行比较。

In Python, how do you convert a `datetime` object to seconds?

对我来说更复杂:

durSec = time.mktime(time.strptime(data[7], "%Y-%m-%d %H:%M:%S")) - time.mktime(time.strptime(data[6], "%Y-%m-%d %H:%M:%S"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 2013-12-06
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多