Format String "28122016" for date "2016-12-28"

10

I know it's a simple question, but I've done a lot of research and I'm not finding a simple solution. I need to create a function that receives a date in "28122016" format and converts it to "2016-12-28" . How can I do this?

    
asked by anonymous 24.01.2017 / 12:49

2 answers

18

The best solution is to use the ready-made functions in the datetime package. Example:

from datetime import datetime
d = datetime.strptime('28122016', '%d%m%Y')
print(d.strftime('%Y-%m-%d'))

See working on Ideone .

But if you prefer (and if it is a quick and quick thing), you can also do it manually:

data = '28122016'

dia = int(data[:2])
mes = int(data[2:4])
ano = int(data[4:])

print('{:4d}-{:2d}-{:2d}'.format(ano, mes, dia))

See working on Ideone .

    
24.01.2017 / 13:00
9

Solution

If you are sure that the format to be treated will always be ddmmyyyy , you can create a function as follows:

my_date = lambda d: "{}-{}-{}".format(d[4:8], d[2:4], d[0:2])

To use it, just invoke it as follows: my_date("28122016") . The result should be 2016-12-28 .

  

You can see the code working here , just press the Run button to execute the script.

Explanation

The solution makes use of the format method present in objects of type string natively. By {} the new text format is defined, replacing each {} with its value passed to the method.

In this case, the first {} will be replaced by the value of d[4:8] , where d is the value passed by the parameter when invoking the function. Since the string can be seen as a vector of characters, when using d[4:8] , we are accessing the characters in positions 4 to 8, exclusive, that is, 4, 5, 6 and 7, which will represent the year of the date. The second {} will be replaced by the value of d[2:4] , which will represent the month, and the third {} by the value of d[0:2] , which will represent the day.

If you need more complex operations than this, you can use the named parameter version of the format method, as follows:

my_date = lambda d: "{year}-{month}-{day}".format(day = d[0:2], month = d[2:4], year = d[4:8])

The result will be exactly the same, but with the most readable format for humans.

  

For more information about the format method, click here . Official strings documentation: here .

    
24.01.2017 / 13:17