[Tutor] stripping 0's from 01's - 09's

Lie Ryan lie.1296 at gmail.com
Fri Jun 5 08:11:28 CEST 2009


Norman Khine wrote:
> Hello,
> Simple, I guess, but I am trying to do a formated date function, which
> I have working but for a small annoyance in that:
> 
>>>> from datetime import date
>>>> def format_date(day):
> ....     if day > 3 and day < 14:
> ....             return '%b %dth %Y'
> ....     indicator = day % 10
> ....     if indicator == 1:
> ....             return '%b %dst %Y'
> ....     elif indicator == 2:
> ....             return '%b %dnd %Y'
> ....     elif indicator == 3:
> ....             return '%b %drd %Y'
> ....     else:
> ....             return '%b %dth %Y'
> ....
>>>> today = '2009-06-04'
>>>> year, month, day = today.split('-')
>>>> date_object = date(int(year), int(month), int(day))
>>>> format = format_date(date_object.day)
>>>> formated_date = date_object.strftime(format)
>>>> formated_date
> 'Jun 04th 2009'
> 
> It will be much better to have:
> 
> 'Jun 4th 2009'
> 
> How would you go about in doing this?
> 
> Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

instead of using '%d' use '%e'

>>> import datetime
>>> from string import letters
>>> letters = ['%%%s' % let for let in letters]
>>> letters
['%a', '%b', '%c', '%d', '%e', '%f', '%g', '%h', '%i', '%j', '%k', '%l',
'%m', '%n', '%o', '%p', '%q', '%r', '%s', '%t', '%u', '%v', '%w', '%x',
'%y', '%z', '%A', '%B', '%C', '%D', '%E', '%F', '%G', '%H', '%I', '%J',
'%K', '%L', '%M', '%N', '%O', '%P', '%Q', '%R', '%S', '%T', '%U', '%V',
'%W', '%X', '%Y', '%Z']
>>> d = datetime.date(*map(int, '2009-06-05'.split('-')))
>>> formats = ['%s: %s' % (let, d.strftime(let)) for let in letters]
>>> for x in formats: print x
...
%a: Fri
%b: Jun
%c: Fri Jun  5 00:00:00 2009
%d: 05
%e:  5
%f: %f
%g: 09
%h: Jun
%i: %i
%j: 156
%k:  0
%l: 12
%m: 06
%n:

%o: %o
%p: AM
%q: %q
%r: 12:00:00 AM
%s: 1244124000
%t: 	
%u: 5
%v: %v
%w: 5
%x: 06/05/09
%y: 09
%z:
%A: Friday
%B: June
%C: 20
%D: 06/05/09
%E: %E
%F: 2009-06-05
%G: 2009
%H: 00
%I: 12
%J: %J
%K: %K
%L: %L
%M: 00
%N: %N
%O: %O
%P: am
%Q: %Q
%R: 00:00
%S: 00
%T: 00:00:00
%U: 22
%V: 23
%W: 22
%X: 00:00:00
%Y: 2009
%Z:

I don't know why %e is not in the docs though, can anyone confirm
whether this is a doc bug or an undocumented (and therefore unreliable)
feature leaked from the underlying C library?

And anyone know what's wrong with %n since it seems it produces a "\n"
(newline) character.

Note: %z and %Z are for timezone data (e.g. +0500 or EST). Since my
sample data does not account for timezone it is now empty (as documented)



More information about the Tutor mailing list