-3

EDIT: It seems my error was caused by a simple oversight on my part & should be and in python. Thanks for the help everyone!

I'm trying to teach myself python and as such I want to make a simple script that calculates my hours worked for my current job. It seems I can't find any good sources on how to use regex expressions in conditional if and elif statements.

What I'm trying to do is check if my start time has a period of am or pm and whether my end time has a period of am or pm this way depending on the combination I can add the total hours worked up accurately.

To do this I am using regex to check the end of my input for am or pm. I then see which combination the times I sent in have, e.g. start_time = 8:00am and end_time = 11:23am so this should have matches for start_match_am and for end_match_am

My complete code is as follows:

import re
pattern = re.compile('^([0-1]?[0-9]):[0-5][0-9][aApPmM]{2}$')
start_time = ""
end_time = ""
hours_worked = 0.0

start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
while re.match(pattern, start_time) == False:
    print("I'm sorry the time must be in the format -- HH:MMam or H:MMpm \n")
    start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
end_time = input("Please enter the time you stopped working(ex -- 5:00pm): \n")
while re.match(pattern, end_time) == False:
    print("I'm sorry the time must be in the format -- HH:MMam or H:MMpm \n")
    end_time = input("Please enter the time you stopped working(ex -- 8:00am): \n")
start_hour = int(start_time[:(start_time.find(':'))])
start_minutes = int(start_time[(start_time.find(':') + 1):-2])
end_hour = int(end_time[:(end_time.find(':'))])
end_minutes = int(end_time[(end_time.find(':') + 1):-2])
start_period = start_time[start_time.find(':')+3:]
end_period = end_time[end_time.find(':')+3:]
pattern_am = re.compile('am', re.I)
pattern_pm = re.compile('pm', re.I)
start_match_am = re.match(pattern_am, start_period)
start_match_pm = re.match(pattern_pm, start_period)
end_match_am = re.match(pattern_am, end_period)
end_match_pm = re.match(pattern_pm, end_period)
if start_match_am is not None & end_match_am is not None:
    total_hours = end_hour - start_hour
    total_minutes = (end_minutes - start_minutes+60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")
elif start_match_pm is not None & end_match_pm is not None:
    total_hours = end_hour - start_hour
    total_minutes = (end_minutes - start_minutes+60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")
elif start_match_am is not None & end_match_pm is not None:
    total_hours = end_hour + 12 - start_hour
    total_minutes = (end_minutes - start_minutes + 60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")
elif start_match_pm is not None & end_match_am is not None:
    total_hours = end_hour + 12 - start_hour
    total_minutes = (end_minutes - start_minutes + 60) % 60
    print("You worked for "+total_hours+"hr "+total_minutes+"min")

First I want to say I know I don't handle adding minutes together correctly at the moment, I wrote that when I was very tired and will be fixing when I get the regex to work. The issue specifically is happening at this line:

if start_match_am is not None & end_match_am is not None:

The error I get is:

Please enter the time you started working(ex -- 8:00am): 
8:00am
Please enter the time you stopped working(ex -- 5:00pm): 
11:23am
Traceback (most recent call last):
  File "/home/primus/PycharmProjects/HoursWorks/venv/HoursWorked/CalculateHours.py", line 27, in <module>
    if start_match_am is not None & end_match_am is not None:
TypeError: unsupported operand type(s) for &: 'NoneType' and '_sre.SRE_Match'

Process finished with exit code 1

This has really stumped me as the following posts on here specifically state this is how you use regex in conditional if statements:

Python: How to use RegEx in an if statement?

Regular Expression in conditional statement using Python 3

If anyone can point out a simple mistake I'm making or let others in a similar situation to me know how to properly use regex in conditional if statements in python 3 it would be much appreciated!

  • 2
    `&` should be `and` –  Sep 30 '18 at 22:01
  • tl;dr - but regarding your conditional for testing if a string ends with `am` or `pm`, don't use `re`. Use `str.endswith('am')` or `str.endswith('pm')`. E.g. `In: '8:00 pm'.endswith('pm') --> Out: True` and `In: '8:00 pm'.endswith('am') --> Out: False`. The same of course with string variables instead of constants. – SpghttCd Sep 30 '18 at 22:02
  • @JETM wow now I feel dumb can't believe I didn't look that up. – ego_sum_primus Sep 30 '18 at 23:14
  • Also @SpghttCd does str.endswith() work with mismatched cases? – ego_sum_primus Sep 30 '18 at 23:14

2 Answers2

1

re.search returns either a match object or None. First, call re.search and store its value in a variable and then test if it is None. Just make sure you test if it is not None, before you try to extract values from it.

Also, you don't need to use is not None to check if something is equal to none, simply test it as if it were a boolean.

Finally, you seem to want to extract data from a regular expression. If you want to do this, you can call group(0) on the regex to get the content of the match (actually the first group, but you read more about this on the regex page, this should work for your purposes). Then convert the result to whatever you need. For example, you can find and extract the first number in a string and test if it is greater than some value like the following:

import re

my_str = input()
match = re.search(r'\d+', my_str)

if match and int(match.group(0)) > 10:
     print('The input was greater than 10.')

Hope this helps. Go check out the docs if you want to see more on regexes. Docs: https://docs.python.org/3/library/re.html

ComedicChimera
  • 466
  • 1
  • 4
  • 15
0

Please note that I'm aware that my answer is not an answer to your question - however, I feel like it's still important to tell you the following.

Regex is a very powerful tool, which has it's target applications or problems to be solved with. But IMO, yours is not a regex topic.

There is a library for python which can deal with date and time. Please consider using an approach like this one:

import datetime as DT

start_time = input("Please enter the time you started working(ex -- 8:00am): \n")
incorr_ans = True
while incorr_ans:
    try:
        s_t = DT.datetime.strptime(start_time, '%I:%M%p')
        incorr_ans = False
    except:
        start_time = input("Please enter the time you started working(ex -- 8:00am): \n")

end_time = input("Please enter the time you stopped working(ex -- 8:00am): \n")
incorr_ans = True
while incorr_ans:
    try:
        e_t = DT.datetime.strptime(end_time, '%I:%M%p')
        incorr_ans = False
    except:
        end_time = input("Please enter the time you stopped working(ex -- 8:00am): \n")

print(s_t, e_t)
print(e_t - s_t)

Note that the major part of the program is because of the doubled error catching of user input. But still I think this is a very convenient way. And: your complicated calculation is just a simple substraction here...
So this will lead to a program from user perspective like:

Please enter the time you started working(ex -- 8:00am): 
8:34am

Please enter the time you stopped working(ex -- 8:00am): 
3:07pm
1900-01-01 08:34:00 1900-01-01 15:07:00
6:33:00

Just watch through it, perhaps you'll like it and work on in this direction by yourself. And still, if you really have to test re because it's so interesting - there'll be other problems for that...

SpghttCd
  • 10,510
  • 2
  • 20
  • 25
  • Thank you, I was initially looking into using this library but from the research I had done could not tell if I could use it to hold the time I was inputting and as such decided to go with regex. I had previously learned regex in one of my classes and wanted to try it out in this scenario. I think I will stick with regex just because it will be easier to get my answer in a format that I can just copy into my time sheet for work lol. I will definitely try this library out in a future project though so thank you again! – ego_sum_primus Sep 30 '18 at 23:21
  • ;-)... "lol" is _exactly_ the right comment to this reason... What format are you talking about? – SpghttCd Oct 01 '18 at 04:47