[sf-lug] unix time conversion

Alex Kleider a_kleider at yahoo.com
Mon Oct 27 19:15:42 PDT 2008


--- On Mon, 10/27/08, Jeffrey Malone <ieatlint at tehinterweb.com> wrote:

> strptime() is indeed the correct function.
> See http://www.python.org/doc/2.5.2/lib/module-time.html
> for usage
> information (it's formatting borrows the strftime
> conversion
> specifiers as described in that big table)
> 
> Here is how you do it:
> 
> import time
> string = "July 3, 1945"
> 
> 
> # This reads the string as a time value structure.  You
> copy for the
> formatting of the string above, replacing
> # the variables with conversion specifiers (eg,
> "%B").  Notice how the
> comma is written after the %d, just as it is after the
> numeral 3 in
> the string.
> timestruct = time.strptime( string, "%B %d, %Y" )
> # Note that when you imprecisely give it a time it will
> fill in
> undefined values with defaults.
> # In this case, we did not specify a the hour, minute,
> second (and a
> couple other things).  As such, they will default to 0 --
> meaning, it
> will read the time as "July 3, 1945 00:00:00" (as
> in, midnight).
> # Also, as this is a UNIX epoch, it is without timezone,
> which can be
> worth noting to avoid potential confusion.
> 
> # mktime takes a time value struct and returns a UNIX epoch
> timestamp
> representing it (as a float -- although with this usage it
> should
> always be an integer)
> epoch = time.mktime( timestruct )
> 
> print epoch
> ##eof
> 

Thanks for the tip; I had already printed out the url you suggested but found it confusing. Perhaps later in the ThinkPython class we can look at that for extra credit:-)




      




More information about the sf-lug mailing list