【问题标题】:How to get just the hours and minutes from a datetime object [duplicate]如何从日期时间对象中获取小时和分钟[重复]
【发布时间】:2018-07-10 18:27:53
【问题描述】:

我目前有一个程序可以跟踪一个人何时登录,以及他们何时因不和谐而退出。该程序以日期时间对象的形式给出了签署时间和签署时间,并将它们彼此相减,得到总数。问题是我希望它只给我小时和分钟,而不是秒和毫秒。 代码如下:

@bot.event
async def on_message(message):
    if "on" in message.content:
        player = message.author
        time = message.timestamp
        message_type = 'on'
        with open(str(player) + " on", 'w') as f:
            f.seek(0)
            f.truncate()
            f.write(str(time))
    elif "off" in message.content:
        player = message.author
        off_time = message.timestamp
        with open(str(player) + " on",'r+') as f:
            on_time = f.readline()
            f.seek(0)
            f.truncate()
        on_time = parser.parse(on_time)
        total = off_time - on_time
        print(total)

注意:total对象是timedelta对象,不是timedate对象。

【问题讨论】:

  • 不幸的是,虽然第一个 dup 有你想要的答案,但它不是那里接受的答案。所以你必须去the second answer

标签: python python-3.x


【解决方案1】:

.minute\.hour 属性以int 的形式为您提供信息

import datetime
datetime.datetime.now().minute
datetime.datetime.now().hour

如果您想获取新的日期时间对象,请使用replace 方法:

datetime.datetime.now().replace(second=0, microsecond=0)

对于timedelta 对象,使用.total_seconds() 方法

timedelta_obj = datetime.datetime(2018,1,2) - datetime.datetime(2018,1,1)
seconds = timedelta_obj.total_seconds()
rounded_minute = round(seconds/60)

【讨论】:

  • 但是如何在我的代码中使用它呢?我想使用我已经制作的对象
  • 这是一个 timedelta 对象,而不是一个 datetime 对象
  • 当我做出原始答案时,带有注释的编辑不存在。添加了timedelta 的答案。
  • 那不是要花时间吗?我希望它从名为 total 的 timedelta 中获取它
猜你喜欢
  • 2019-12-22
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多