0

I'm trying to convert a date that is in the format of YYYYMMDD to MM/DD/YYYY as it is being read from a database and written to an Excel file. Using Perl I would do the following:

var=~s/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])/$5$6\/$7$8\/$1$2$3$4/;

Keeping in mind that this is all happening in a "for row in rows" loop structure that is reading in the database info.

Any help would be very much appreciated.

1
  • 1
    Have you looked at the re module at all? Commented Dec 13, 2012 at 16:15

4 Answers 4

4

instead of using a regular expression you can use pythons datetime module.

or you could combine the two, however it is you want, but this would be a more clear way to modify date formatting. python is a language where clarity and easy reading are as important as efficiency. looking at the code below one can see that i am modifying a datestamp, whereas using a regular expression it is quite unclear sometimes.

read the datetime element and then write it as you want:

>>> from datetime import datetime
>>> datestring = '20121212' # 2012 / 12 /12 
>>> datetime.strptime(datestring, '%Y%m%d').strftime('%m/%d/%Y')
'12/12/2012'
Sign up to request clarification or add additional context in comments.

Comments

2

You don't need to use a regex -- Python doesn't encourage them in the same way Perl does -- but you can certainly use one:

import re 
re.sub(r'(\d{4})(\d{2})(\d{2})', r'\2/\3/\1', datestring)

1 Comment

Thank you for the VERY quick response. I ended up doing:
2

I would go for simple string operations - certainly no less clear...

>>> s = '20121213'
>>> '/'.join( (s[4:6], s[6:], s[:4]) )
'12/13/2012'

as opposed to:

>>> re.sub(r'(\d{4})(\d{2})(\d{2})', r'\2/\3/\1', s)
'12/13/2012'

If you're going to insist using an re like you've posted below though

dateFormatted = row["TRADE_DATE"] dateFormatted = re.sub(r'(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)', r'\5\6/\7\8/\1\2\3\4', dateFormatted) – user1901341 5 mins ago

Then you could (ab)use string formatting as such

>>> '{4}{5}/{6}{7}/{0}{1}{2}{3}'.format(*s)
'12/13/2012'

1 Comment

dateFormatted = row["TRADE_DATE"] dateFormatted = re.sub(r'(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)', r'\5\6/\7\8/\1\2\3\4', dateFormatted)
0

I think you can get to it simply here, without regex:

>>> s = '20121225'
>>> conv = '/'.join((s[6:8], s[4:6], s[0:4]))
>>> conv
'25/12/2012'

1 Comment

Thank you for the timely response and elegant solution.

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.