By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,965 Members | 1,962 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,965 IT Pros & Developers. It's quick & easy.

Split a date string on a variable character

P: n/a
I need to search characters inside a date string so that I can split the string.

date = '02/03/2010'

The date separators could be ('/', ' ', '-', '.')
Oct 29 '10 #1
Share this Question
Share on Google+
6 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Expand|Select|Wrap|Line Numbers
  1. >>> possible_characters = ('/', ' ', '-', '.')
  2. >>> date = '02/03/2010'
  3. >>> re.split("[%s]" % ("".join(possible_characters)), date)
  4. ['02', '03', '2010']
  5. >>> 
Oct 29 '10 #2

P: n/a
The original result is what I'm looking for, especially if it works no which mix of characters separates the date in the original string. ie. date = '02/03-2010'


>>> findChar = ('/',' ','-','.',',')
>>> date = '02/03/2010'
>>> re.split("[%s]" % ("".join(findChar)),date)

Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
re.split("[%s]" % ("".join(findChar)),date)
NameError: name 're' is not defined


changed re to date
>>> date.split('[%s]' % (''.join(findChar)),date)

Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
date.split('[%s]' % (''.join(findChar)),date)
TypeError: an integer is required
Oct 29 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
I left out a critical line of code:
Expand|Select|Wrap|Line Numbers
  1. import re
Module re is not built-in.
Oct 29 '10 #4

P: n/a
Thanks for the help, it's working perfectly. Could you explain the details of the re.split line of code? I understand about half of what is going on. I read the help(re), but am still scratching my head wondering how it works.

Thanks
Oct 30 '10 #5

P: n/a
Is it possible to use ',' as one of the date separators?
When I add the comma to my list of separators I get an error. Without the comma in the list the program works fine. If I run the dateParts lines from the python shell it separates the comma just fine.

Traceback (most recent call last):
File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 112, in <module>
today = Date(date)
File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 20, in __init__
self._date = self.convertDate() #convert the date to the proper format
File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 31, in convertDate
parts = self.dateParts()
File "F:\CSIS 152\project 9\David Peterson ex7_11.py", line 40, in dateParts
dateParts = re.split("[%s]" % (''.join(separators)),self._date) #import re for this command to work
File "C:\Python27\lib\re.py", line 167, in split
return _compile(pattern, flags).split(string, maxsplit)
File "C:\Python27\lib\re.py", line 245, in _compile
raise error, v # invalid expression
error: bad character range
Expand|Select|Wrap|Line Numbers
  1. class Date:
  2.     """Class for storing dates"""
  3.  
  4.     MONTHNAMES = ['January', 'February', 'March', 'April',
  5.     'May', 'June', 'July', 'August', 'September', 'October',
  6.     'November', 'December']
  7.  
  8.     MONTHLENGTHS = ['31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31']
  9.  
  10.     def __init__(self, date):
  11.         '''Constructor'''
  12.         self._date = date
  13.         self._date = self.convertDate() #convert the date to the proper format
  14.  
  15.     def __str__(self):
  16.         '''Display the date in Month XX, YYYY format'''
  17.         #pass
  18.         return self._date
  19.  
  20.  
  21.     def convertDate(self):
  22.         '''Converts the given date into format Month XX, YYYY format'''
  23.         #pass
  24.         parts = self.dateParts()
  25.         if not parts[0] in Date.MONTHNAMES:
  26.             parts[0] = Date.MONTHNAMES[int(parts[0])-1]
  27.         date = parts[0] + ' ' + parts[1] + ', ' + parts[2]
  28.         return date
  29.  
  30.     def dateParts(self):
  31.         '''Separates the date into parts: month, day, and year.'''
  32.         separators = ('/', ' ', '.', '-', ',')
  33.         dateParts = re.split("[%s]" % (''.join(separators)),self._date) #import re for this command to work
  34.         return dateParts
Oct 30 '10 #6

bvdet
Expert Mod 2.5K+
P: 2,851
The re module is used to perform regular-expression pattern matching and replacement in strings. Instead of me trying to explain further, look at this tutorial.

Reordering the separators seems to work. I don't know why.

Remember to use code tags!
Expand|Select|Wrap|Line Numbers
  1. separators = (',', '/', ' ', '.', '-')
Oct 30 '10 #7

Post your reply

Sign in to post your reply or Sign up for a free account.