sscanf needed

Andrew E andrew at nospam.com
Sun Apr 17 11:46:53 EDT 2005


Uwe Mayer wrote:
> Hi,
> 
> I've got a ISO 8601 formatted date-time string which I need to read into a
> datetime object.
> Is there a shorter way than using regular expressions? Is there a sscanf
> function as in C?

in addition to the other comments...

I like re, because it gives me the most control. See below.


import re
import datetime

class Converter:
	
	def __init__( self ):
		self.isoPattern = re.compile( "(\d\d\d\d)-(\d\d)-(\d\d)[tT
](\d\d):(\d\d):(\d\d)" )
		
	def iso2date( self, isoDateString ):
		match = self.isoPattern.match( isoDateString )
		if not match: raise ValueError( "Not in ISO format: '%s'" %
isoDateString )
		
		return datetime.datetime(
			int(match.group(1)),
			int(match.group(2)),
			int(match.group(3)),
			int(match.group(4)),
			int(match.group(5)),
			int(match.group(6))
			)

c = Converter()


def demo( iso ):
	try:
		date = c.iso2date( iso )
		print "Input '%s' -> datetime: %s" % ( iso, date )
	except ValueError, e:
		print str(e)
		
demo( "2005-04-21T12:34:56" )
demo( "2005-04-21 12:34:57" )
demo( "2005-04-2 12:34:57" )





More information about the Python-list mailing list