Mailing List Archive

Date formats
I read the documentation in the Python Reference Library (6.3) on time
access and conversions and chapter 8 in programming python, yet I can't
figure out if i need ( or how to use) a tuple to format the return from
localtime(). i get a string now (wed jun 10 1999 xx:xx:xx) but i need
to format it to yyyymmdd_hhmmss. Is there any switch ( %) or function
that can be useful? Any help is appreciated.
--mike
Date formats [ In reply to ]
mike milliger <milliger@ausinfo.com> wrote:
: I read the documentation in the Python Reference Library (6.3) on time
: access and conversions and chapter 8 in programming python, yet I can't
: figure out if i need ( or how to use) a tuple to format the return from
: localtime(). i get a string now (wed jun 10 1999 xx:xx:xx) but i need
: to format it to yyyymmdd_hhmmss. Is there any switch ( %) or function
: that can be useful? Any help is appreciated.

"Here strftime comes to save the day!" (Okay, I won't do my bad
impressions of Andy Kaufman anymore.)

The time module has a handy function called strftime, which works like
format strings, but on the time tuple.

my_date = time.strftime("%Y%m%d_%H%M%S", time.localtime(time.time()))
print my_date
19990610_145144

Or you can look at the less-standard, more versatile mxDateTime package
(http://starship.python.net/~lemburg/mxExtensions.html).

-Arcege
Date formats [ In reply to ]
On 10 Jun 99, mike milliger wrote:

> I read the documentation in the Python Reference Library (6.3) on time
> access and conversions and chapter 8 in programming python, yet I can't
> figure out if i need ( or how to use) a tuple to format the return from
> localtime(). i get a string now (wed jun 10 1999 xx:xx:xx) but i need
> to format it to yyyymmdd_hhmmss. Is there any switch ( %) or function
> that can be useful? Any help is appreciated.

You can roll your own:

#

import time

t = time.localtime(time.time())
# prints the tuple
print t

# prints a formatted tuple
print "%d%02d%02d_%02d%02d%02d" % t[0:6]

Disclaimer: This is untested, maybe the format will appear weird...
but you'll get the idea.

Veel liefs,

--Hans Nowak (ivnowa@hvision.nl)
Homepage: http://fly.to/zephyrfalcon
Date formats [ In reply to ]
mike milliger wrote:
>
> I read the documentation in the Python Reference Library (6.3) on time
> access and conversions and chapter 8 in programming python, yet I can't
> figure out if i need ( or how to use) a tuple to format the return from
> localtime().

Mike,

You want to use time.strftime if it's available on your platform.
Here's a simple example:

>>> import time
>>> now = time.localtime(time.time())
>>> now
(1999, 6, 11, 15, 48, 40, 4, 162, 1)
>>> time.strftime("%m/%d/%y", now)
'06/11/99'
>>> time.strftime("%Y-%m-%d", now)
'1999-06-11'

--
Skip Montanaro | Mojam: "Uniting the World of Music"
http://www.mojam.com/
skip@mojam.com | Musi-Cal: http://www.musi-cal.com/
518-372-5583