Home > Back-end >  How to search a string for the first and second occurance of military time in python
How to search a string for the first and second occurance of military time in python

Time:04-07

So I'm doing some scraping in my django application.

The thing that I get when scraping contains a date element which looks something like this

7 april 2022 19:00 - 8 april 04:00 utc 02

I have already figured out how to pull the start day and both of the months, I am however having some trouble pulling the military times as well as the second day.

I'm thinking that I have to use the % operator in some way when searching for the military time but couldn't find much online and its been a while since I used python.

For the pulling of the second day I tried to do the same thing as I did when taking the first one the problem is however that i end up pulling the "02" from the "utc 02".

Thanks for any help I can get!

time = temp[0]  # the content of scraping

        emp_str = ""
        f_digit = False
        for d in time:  # finds the first digit(s) aka the day
            if d.isdigit():
                emp_str = emp_str d
                f_digit = True
            elif f_digit:
                break
        s_day = emp_str
        emp_ar = []
        s_month = ""
        e_month = ""
        for m in MONTHS:  # this finds the months in the string and adds their index for comparing MONTHS contains the months aka apr jun jul and so on
            index = time.find(m)
            if index != -1:
                emp_ar.append(m)
                emp_ar.append(index)

        if len(emp_ar) > 2:
            print("happened")
            # checks which index is bigger aka which one is mentioned first
            if int(emp_ar[1]) < int(emp_ar[3]):
                s_month = emp_ar[0]
                e_month = emp_ar[2]
            else:
                s_month = emp_ar[2]
                e_month = emp_ar[0]
        elif len(emp_ar) > 0:
            s_month = emp_ar[0]
            e_month = emp_ar[0]
        # puts the month in s/e month for start/end

CodePudding user response:

You can use the datetime.datetime.strptime() method.

In the comments the format seems to have changed but going off the original format your code would have to look like this:

from datetime import datetime

s = '7 april 2022 19:00 - 8 april 04:00 utc 02'
s = s.split('-')

startdate = datetime.strptime(s[0].strip(), '%d %B %Y %H:%M')
enddate = datetime.strptime(s[1].strip() '00', '%d %B %H:%M utc%z')
startdate = startdate.replace(tzinfo=enddate.tzinfo)
enddate = enddate.replace(year=startdate.year)

Edited to transfer the start year to the end year

  • Related