0

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?

Alan
  • 509
  • 4
  • 15
  • if you don't want to use the `datetime` for whatever reason; you would have to a) make sure that the input is always valid b) then can simply do string manipulation like `'{}-{}-{}'.format(input_date[0:4], input_date[4:6], input_date[6:8])` assuming `input_date` is a valid input date string. – Vikas Prasad May 06 '20 at 03:47
  • 2
    What's wrong with converting to datetime? It gives you extra data validation for free. – COVFEFE-19 May 06 '20 at 03:51
  • It's just an extra module to import so was wondering if there was a simpler solution. However good point about data validation. – Alan May 06 '20 at 07:03
  • The standard way to do this is with the `datetime` module, which is part of the standard library. See [Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python](https://stackoverflow.com/q/43133605/7758804) and [How to convert integer into date object python?](https://stackoverflow.com/q/9750330/7758804) – Trenton McKinney Apr 18 '22 at 21:02

5 Answers5

3

You can slice and format

>>> date = '20190501'
>>> newdate = "{}-{}-{}".format(date[:4],date[4:6],date[6:])
>>> newdate
'2019-05-01'
tdelaney
  • 73,364
  • 6
  • 83
  • 116
3

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:]
Jarred Parrett
  • 101
  • 1
  • 5
1

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])
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

Try this:

before = '20190501'
print('before:', before)
after = ''.join((before[:4],'-',before[4:6],'-',before[6:]))
print('after:', after)
MMEK
  • 70
  • 5
0

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

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
JckHm3r
  • 81
  • 4