1

I have this launch_time:

2015-01-15 10:31:54+00:00

I get current_time

current_time = datetime.datetime.now(launch_time.tzinfo)

I want both of times are same so I used tzinfo. So, the value of current_time is

2015-01-16 10:55:50.200571+00:00

I take the running time with this:

running_time = (current_time - launch_time).seconds/60

The value return only 23 minutes. It should be one day + 23 minutes = 1463 minutes

Can someone help me. Thanks

Ragnarsson
  • 1,715
  • 7
  • 41
  • 74

2 Answers2

9

You are ignoring the .days attribute of the returned timedelta object. Use timedelta.total_seconds() instead to include those in one value:

running_time = (current_time - launch_time).total_seconds()/60

or explicitly use it if you want to ignore the microseconds portion of the delta:

running_time = current_time - launch_time.total_seconds()
running_time = running_time.seconds / 60 + running_time.days / 1440

From the documentation for timedelta.total_seconds():

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Beware, launch_time and current_time may have different UTC offsets i.e., unless launch_time.tzinfo is an instance of pytz timezone (that stores historical (past/future) tz data) then your code is wrong. Convert launch_time to UTC first instead:

from datetime import datetime

launch_time_in_utc = launch_time.replace(tzinfo=None) - launch_time.utcoffset()
elapsed = (datetime.utcnow() - launch_time_in_utc)

where elapsed is the elapsed time since the launch time expressed as timedelta object.

To convert timedelta object to minutes in Python 3.2+:

from datetime import timedelta

elapsed_minutes = elapsed // timedelta(minutes=1)

On older Python versions you could use .total_seconds() as @Martijn Pieters suggested:

elapsed_minutes = elapsed.total_seconds() // 60

Note: // uses an integer division.

See also, Find if 24 hrs have passed between datetimes - Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670