Search code examples
pythondatetimesubstringpython-re

How to search for string between whitespace and marker? Python


My problem is the following: I have the string:

datetime = "2021/04/07 08:30:00"

I want to save in the variable hour, 08 and I want to save in the variable minutes, 30

What I've done is the following:

import re
 
pat = re.compile(' (.*):')
hour = re.search(pat, datetime)
minutes = re.search(pat, datetime)
print(hour.group(1))
print(minutes.group(1))

What I obtain from the prints is 08:30 and 30, so the minutes are correct but for some reason that I'm not understanding, in the hours the first : is skipped and takes everything from the whitespace to the second :.

What am I doing wrong? Thank you.


Solution

  • Ah, no no, python has a much better approach with datetime.strptime

    https://www.programiz.com/python-programming/datetime/strptime

    So for you:

    from datetime import datetime
    
    dt_string = "2021/04/07 08:30:00"
    
    # Considering date is in dd/mm/yyyy format
    dt_object1 = datetime.strptime(dt_string, "%Y/%m/%d %H:%M:%S")
    

    You want hours?

    hours = dt_object1.hour
    

    or minutes?

    mins = dt_object1.minute
    

    Now, if what you have presented is just an example of where you need to work around whitespace, then you could split the string up. Again with dt_string:

    dt_string1 = dt_string.split(" ")
    dateString = dt_string1.split("/")  # A list in [years, months, days]
    timeString = dt_string2.split(":")  # A list in [hours, minutes, seconds]