1

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?

Pythonist
  • 1,937
  • 1
  • 14
  • 25
  • 2
    Please read this: https://stackoverflow.com/questions/10663093/use-python-format-string-in-reverse-for-parsing . "The parse module is the opposite of format()". – Stefano Fiorucci - anakin87 Mar 27 '21 at 11:57
  • 2
    If you're only working with dates/times, you should have a look at [datetime.strptime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior). – Thierry Lathuille Mar 27 '21 at 12:01

1 Answers1

1

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)
ScootCork
  • 3,411
  • 12
  • 22