-1

I need to compare two times in Python.

At first I get the current time:

current_time = time.strftime("%H:%M:%S")

I get another time value from list:

another_time =  datetime.strptime(some_list[2],'%H:%M:%S')

I want to get the difference between those two times in minutes.I've tried to do this:

time_now = datetime.strptime(current_time, '%H:%M:%S')
d1 = time.mktime(another_time.timetuple())
d2 = time.mktime(time_now.timetuple())
diff = (d2-d1) / 60

What I get is:

-1206.0333333

When I print out another_time I get:

1900-01-01 21:07:23

and current_time:

1900-01-01 01:01:21

So the difference should be 238 minutes.

Is the problem in the year (where does this year come anyway?)? Or what should I change in my code?

user3019389
  • 41
  • 2
  • 6

3 Answers3

0

I think this is what you want to do:

from datetime import datetime
from dateutil.parser import parse

l = ['Last', 'ended:', '2015/01/06', '23:38:34', 'UTC']

another_time = parse(l[2] + ' ' + l[3]) # datetime(2015, 1, 6, 23, 38, 34)
current_time = datetime.now()           # datetime(2015, 1, 7,  1,  1, 21)

elapsed = current_time - another_time
elapsed.total_seconds() // 60  # 82 minutes
elyase
  • 39,479
  • 12
  • 112
  • 119
0

i suggest to convert to Epoch time then subtract

example:

import time
import datetime
import calendar

current_time = int(time.time())

another_time = calendar.timegm(datetime.datetime(2015,01,8,0,0).utctimetuple())


print(datetime.timedelta(seconds=another_time-current_time))

output:

1 day, 0:15:50
Urban48
  • 1,398
  • 1
  • 13
  • 26
0

if you get a timedelta -- by subtracting two datetime.datetime object, for instance -- you can use the total_seconds() method, divide by 60, and cast as an integer.

from dateutil.parser import parse 
timeone = parse("10:00 a.m.") #<type 'datetime.datetime'>
timetwo = parse("12:40 p.m.") #<type 'datetime.datetime'>
td = timetwo - timeone # <type 'datetime.timedelta'>
delta_mins = int(td.total_seconds()/60) #outputs 160
Bee Smears
  • 803
  • 3
  • 12
  • 22