【问题标题】:Calculating Uptime From Date/Time In Python在 Python 中根据日期/时间计算正常运行时间
【发布时间】:2021-01-14 21:37:35
【问题描述】:

由于我使用的 API 返回的日期/时间格式,我在使用 python 计算正常运行时间时遇到问题。

我正在使用请求从 json API 中提取服务启动的时间。 服务器 json API 以 iso1801 格式给出时间/日期。

以下是 API 中的示例:2021-01-14T11:17:44-0800

我需要获取该日期/时间并计算自上述示例日期/时间以来已经过了多少分钟、小时、天和月。 -0800 偏移量会因请求而异,因为我正在检查不同位置的多个服务。

我需要得到一个看起来像这样的字符串输出:

3 天 6 小时 32 分钟

我该怎么做呢?有人可以写一个例子吗?我已经在 python 中编码大约 2 个月了,所以我相对较新。

【问题讨论】:

  • 那么,你需要解析数据和时间吗?试试strptime

标签: python datetime


【解决方案1】:

试试下面的代码sn-p:

import datetime

def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60


dt = '2021-01-14T11:17:44-0800'
dt = dt[:-2] + ':' + dt[-2:]
dt_formatted = datetime.datetime.fromisoformat(dt)
now = datetime.datetime.now(dt_formatted.tzinfo)

difference = days_hours_minutes(now - dt_formatted)
print(difference)

这个例子是时区感知的。您将收到 API 发送给您的时间与 API 回答所涉及的时区中的当前时间之间的时差。

警告: 方法 datetime.fromisoformat 仅适用于 Python 3.7+

【讨论】:

  • 这适用于我的时区 (-0800) 中的服务器,但我基本上需要“现在”时间与您的示例中的“dt”具有相同的偏移量。我将如何替换“now”中的偏移量以匹配“dt”中的偏移量?
  • 示例已经在以下行中做到了:now = datetime.datetime.now(dt_formatted.tzinfo)
猜你喜欢
  • 1970-01-01
  • 2019-11-30
  • 2019-12-19
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多