Trivial Thoughts
Thoughts and discussion on programming projects using the Python language.


Python Sites of Note
Software Development



Recent Posts
 9/23/03
 9/22/03
 9/12/03
 9/11/03
 8/21/03
 7/21/03
 7/17/03
 7/10/03
 7/7/03
 7/1/03
 6/26/03
 6/25/03
 6/18/03
 6/15/03
 6/2/03
 5/28/03


Subscribe to "Trivial Thoughts" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.
 

 

Thursday, September 11, 2003
 

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  comment []    


Click here to visit the Radio UserLand website. © Copyright 2003 Michael Kent.
Last update: 9/23/2003; 1:07:03 PM.
This theme is based on the SoundWaves (blue) Manila theme.
September 2003
Sun Mon Tue Wed Thu Fri Sat
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30        
Aug   Oct

Previous/Next