DenVog
DenVog

Reputation: 4286

Calculating Total Seconds with Time Module

I have a document that contains several time measurements that I want to average, so I'm converting minutes and seconds to total seconds. The file looks something like:

Boring text
time 15:07

Right now I can get there with the following:

if line.startswith('time') :
        rtminutes = re.findall('([0-9][0-9]):', line)
        for min in rtminutes :
            rtmintosec = float(min) * 60

        rtseconds = re.findall(':([0-9][0-9])', line)
        for sec in rtseconds :
            totsecs = rtmintosec + float(sec)
            print ("Total roast time in seconds:", totsecs)

It seems like the better way would be using time and total_seconds.

import time

if line.startswith('time') :
    rt = re.search('\d{2}:\d{2}', line)
    rtime = time.strftime(rt, '%M:%S')
    rtime.total_seconds()

Every time I've attempted a time approach, I get errors along the lines of:

TypeError: strftime() argument 1 must be str, not re.Match

I'm obviously missing the boat somewhere. Suggestions appreciated.

Upvotes: 0

Views: 127

Answers (2)

CACTUS1549
CACTUS1549

Reputation: 1

hi i tested with this code i just removed the \n and its working for me

#line is your line number where the tims is time 15:07
#Boringtext is the file name 

from colorama import Fore, Style
import linecache as s
import time
from datetime import timedelta
from datetime import datetime
def file_len(fname , line):
    return s.getline(fname,line)

line = file_len('Boringtext',2)
if line.startswith('time') :
    rt = line.split(' ')
    rtime = datetime.strptime(rt[1].rstrip("\n"), '%M:%S')  
    t = timedelta(minutes = rtime.minute , seconds  = rtime.second )  
    print(Fore.BLUE,t.total_seconds(),Style.RESET_ALL)

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81594

You need to make sure a match was found, and if so extract the matched string from the re.Match object.

rt = re.search('\d{2}:\d{2}', line)
if rt:  # if rt is None then rt.group() will raise an exception
    rtime = time.strftime(rt.group(), '%M:%S')
    rtime.total_seconds()

Upvotes: 3

Related Questions