6

I have some dates which format is d/m/yyyy (e.g. 2/28/1987). I would like to have it in the ISO format : 1987-02-28

I think we can do it that way, but it seems a little heavy:

str_date = '2/28/1987'
arr_str = re.split('/', str_date)
iso_date = arr_str[2]+'-'+arr_str[0][:2]+'-'+arr_str[1]

Is there another way to do it with Python?

1
  • I have huge list of dates so,my first option would be to copy/paste in a spreadsheet editor like LibreOffice and to change the format cell in order to set the right format but that does not work.. Commented Oct 7, 2012 at 19:27

3 Answers 3

18

You could use the datetime module:

datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()

or, as running code:

>>> import datetime
>>> str_date = '2/28/1987'
>>> datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()
'1987-02-28'
Sign up to request clarification or add additional context in comments.

Comments

6

I would use the datetime module to parse it:

>>> from datetime import datetime
>>> date = datetime.strptime('2/28/1987', '%m/%d/%Y')
>>> date.strftime('%Y-%m-%d')
'1987-02-28'

1 Comment

.isoformat() on dates uses the same formatting string OOTB. :-)
1

What you have is very nearly how I would write it, the only major improvement I can suggest is using plain old split instead of re.split, since you do not need a regular expression:

arr_str = str_date.split('/')

If you needed to do anything more complicated like that I would recommend time.strftime, but that's significantly more expensive than string bashing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.