Search code examples
pythonformattingpython-ref-string

How to write a function that retrieves dates from strings arbitrarily formatted


In a nutshell, I need to reverse the operation of Python f-string.

Using this formatter, in Python you can easily build arbitrary strings from variables that contain dates. For example:

f"{day}-{mon}-{year}   \n {hour}:{minute}some silly\n text here_{seconds}"

where year etc. are integers that represent what you'd expect.

Now, I need a function that is able to do the reverse operation, i.e. given a string formatted in a funny (but known) way, retrieve the underlying date variables. Something like this:

def retrieve_date(str_date, str_format):        
    # str_date is 27-03-2021   \n 04:11:some silly\n text here_34"
    # str_format is something like "{day}-{mon}-{year}   \n {hour}:{minute}some silly\n text here_{seconds}"

    # some logic

    # return the 6 integers that make up the time stamp  
    return year, month, day, hour, minute, second

How can this be done in Python?


Solution

  • As mentioned in the comments, you can use datetime.strptime. The p stands for 'parse', there is also strftime which you would use to format a date as a specific string.

    from datetime import datetime
    
    str_date = "27-03-2021   \n 04:11:some silly\n text here_34"
    str_format = "%d-%m-%Y   \n %H:%M:some silly\n text here_%S"
    
    def retrieve_date(str_date, str_format):        
        d = datetime.strptime(str_date, str_format)
    
        return d.year, d.month, d.day, d.hour, d.minute, d.second
    
    
    print(retrieve_date(str_date, str_format))
    
    (2021, 3, 27, 4, 11, 34)