mktime and tupples

Thomas Wouters thomas at xs4all.nl
Thu Oct 28 02:58:17 EDT 1999


On Thu, Oct 28, 1999 at 02:21:59PM +1000, Rico Albanese wrote:

> I am writing a web application and I am trying to get a string which
> represents a date (eg. 16071999) and generate from this the
> corresponding Unix Time in secs from Epoch.  So with the following code
> I am trying to generate a tuple which is suitable to pass to
> time.mktime() as a parameter.  I have imported all of the required
> modules but the following code bombs out at the line "thetime=...".  Are
> the variables y, m, d strings? How do I create a tuple (ie. variable
> "atime" below) so that it is a valid parameter for time.mktime()?  Here
> is my code :

You forgot to include the error message, but fortunately my python gave the
same one ;)

> yr=re.search('[0-9]{1,4}$',c_date)  #pull year from 16071999 eg. 1999
> dymnth=re.search('^[0-9]{1,4}',c_date)  #pull out day/month from
> 16071999 eg. 1607
> daymonth=dymnth.group()
> dy=re.search('^[0-9]{1,2}',daymonth)  #pull out day from 16071999 eg. 16
> 
> mnth=re.search('[0-9]{1,2}$',daymonth)  #pull out month from 16071999
> eg. 07
> y=yr.group()
> m=mnth.group()
> d=dy.group()
> atime=(y,m,d,0,0,0,0,0,0)

You're forgetting that re's group() returns strings. Let me guess, you are
used to perls' automatic conversions ? :) y, m and d are strings containing
digits (because that's what you 're' for), so the tuple contains

>>> atime
('1999', '07', '16', 0, 0, 0, 0, 0, 0)

See the difference between the first three elements and the rest ? You need
to convert the strings to ints first:

>>> atime=(int(y),int(m),int(d),0,0,0,0,0,0)
>>> atime
(1999, 7, 16, 0, 0, 0, 0, 0, 0)

Now mktime works properly:

>>> thetime=time.mktime(atime)
>>> thetime
932076000.0
>>> time.ctime(thetime)
'Fri Jul 16 00:00:00 1999'

Couple of other hints though... time.strptime() does mostly what you want
without using nasty regexps ;) See the library reference for more
documentation on it. And dont forget that the python interpreter is very
interactive. You can generally just paste your script into your python
interpreter, and see where it goes wrong, and find out why. Simply printing
atime in your above script would have given a lot more hints. Alternatively,
use python -i, which forces interactive mode after the script finishes...
also great for post-mortem investigations...

A-lot-of-our-knowledge-of-inner-workings-comes-from-postmortems'ly y'rs,
	Thomas
-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list