'Python Convert YYYYMMDD string to YYYY-MM-DD string Without Using Datetime

How can I convert a string such as:

'20190501'

To a string such as:

'2019-05-01'

Without first converting to datetime, for example:

from datetime import datetime
datetime.strptime('20190501', '%Y%m%d').strftime('%Y-%m-%d'))

The above code works, however since I'm starting and ending with a string, it seems unnecessary to use datetime in the process. Can I convert the string directly?



Solution 1:[1]

if the format is always YYYYMMDD it can be converted by getting the terms in the following way:

s="YYYYMMDD"
s=s[:4]+"-"+ s[4:6]+"-"+s[6:]

Solution 2:[2]

You can slice and format

>>> date = '20190501'
>>> newdate = "{}-{}-{}".format(date[:4],date[4:6],date[6:])
>>> newdate
'2019-05-01'

Solution 3:[3]

If you know the format is fixed, it's trivial to do with string slicing.

d = '20190501'
print(d[0:4] + '-' + d[4:6] + '-' + d[6:8])

Solution 4:[4]

Try this:

before = '20190501'
print('before:', before)
after = ''.join((before[:4],'-',before[4:6],'-',before[6:]))
print('after:', after)

Solution 5:[5]

You can use string indexing as follows.

old_date = '20200505'

new_date = old_date[:4]+'-'+old_date[4:6]+'-'+old_date[6:8]

print(new_date)

2020-05-05

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 tdelaney
Solution 3 Mark Ransom
Solution 4 MMEK
Solution 5 Henry Ecker