Python 2.3 and the datetime module
One of the new modules that Python 2.3 gives us is datetime, which I've been itching to get my hands on. Now, M.-A. Lemburg's mxDateTime module has given us Pythonistas date and time handling for some time, but it's always struck me as an 800-lb gorilla. So I was happy to have the trimmed-down alternative.
In addition to all the standard date handling stuff, one capability of mxDateTime I definitely need is the ability to parse a date/time string and create a date/time object from it. For my current project, I need to read in existing schedule information so that I can detect appointment conflicts. So I was concerned that the new datetime module has no string parser.
Upon digging further, though, I found that the module provides a factory function that takes the number of seconds since the epoch (like what is returned by time.time), and returns a datetime object. This didn't give me what I wanted, but it was interesting.
Another interesting addition in Python 2.3 is the new time.strptime function, which parses a date/time string and returns a special sequence called a struct_time. So here we have the string parsing I want, just not the value I need. This is where an adapter would come in handy, and what do you know, there's time.mktime, which takes a struct_time, and returns the corresponding time in seconds since the epoch.
Putting this all together, we have: import time import datetime aDateString = "9/11/2003 12:30" dateParseFormat = "%m/%d/%Y %H:%M" aDateObj = datetime.datetime.fromtimestamp(time.mktime( time.strptime(aDateString, dateParseFormat)))
Now this gives me what I want. I'd rather not have had to do this much work to get it, but hey.
8:04:07 PM
|