-3

I currently have a program that keeps track of when a person signs on, and when they sign off over discord. The program is given the signing on time, and signing off time in the form of a datetime object, and it subtracts them from each other, giving me the total. The problem is I want it to only give me the hours and minutes, not seconds and milliseconds. Code shown below:

@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)

Note: The total object is a timedelta object, not a timedate object.

1
  • Unfortunately, while the first dup has exactly the answer you want, it's not the accepted answer there., so you have to go to the second answer.
    – abarnert
    Jul 10, 2018 at 18:38

1 Answer 1

2

the .minute \ .hour properties gives you the information as an int

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

if you want to get a new datetime object use the replace method:

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

for a timedelta object use the .total_seconds() method

timedelta_obj = datetime.datetime(2018,1,2) - datetime.datetime(2018,1,1)
seconds = timedelta_obj.total_seconds()
rounded_minute = round(seconds/60)
4
  • But how do I use this in my code? I want to use the object I made already Jul 10, 2018 at 18:36
  • It's a timedelta object, not a datetime object Jul 10, 2018 at 18:38
  • the edit with the note was not there when i made the original answer. added the answer for timedelta.
    – moshevi
    Jul 10, 2018 at 18:43
  • Isn't that taking the time from then? I want it to take it from the timedelta called total Jul 10, 2018 at 22:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.