Search code examples
python-datetime

Measure elapsed time from fixed datetime


I am trying to measure how many minutes have elapsed from the time I turn my code from a fixed time, lets say 8:30 am of that day. If I turn my code on at 12am it should see that 210 minutes have elapsed. Any suggestions would help greatly. Thank you


Solution

  • You can import the datetime module, which has a class with the same name, with method datetime.datetime.now().

    This returns an object representing the time when it is called.

    This object has the method replace(), which can be used to 'change' the time to 8:30, if you call it like so - replace(hour=8, minute=30).

    You can then create another similar object but without replacing the time, then you can simply subtract the first from the second to get the elapsed time as a datetime object.

    This will then have elapsed_time.seconds to give you the time change in seconds, which can be divided by 60 if you want for the time in minutes.

    Example

    import datetime
    
    time_A = datetime.datetime.now()
    time_A = time_A.replace(hour=8, minute=30)
    
    time_B = datetime.datetime.now()
    
    elapsed_time = time_B - time_A
    
    print(elapsed_time.seconds, "seconds have passed since 8:30 this morning")
    

    If you wanted this for a specific timezone, you can add or subtract the offset from your current timezone. So if you are for example, 5 hours ahead of CST, you can have it get the difference from 3:30 instead.