1

If I have a datetime object, how would I get the date as a string in the following format:

1/27/1982  # it cannot be 01/27/1982 as there can't be leading 0's

The current way I'm doing it is doing a .replace for all the digits (01, 02, 03, etc...) but this seems very inefficient and cumbersome. What would be a better way to accomplish this?

halfer
  • 19,824
  • 17
  • 99
  • 186
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

4

You could format it yourself instead of using strftime:

'{0}/{1}/{2}'.format(d.month, d.day, d.year) // Python 2.6+

'%d/%d/%d' % (d.month, d.day, d.year)
bobince
  • 528,062
  • 107
  • 651
  • 834
  • 2
    I think it would be nicer as: `'{0.month}/{0.day}/{0.year}'.format(d)` – Jeff Mercado Oct 01 '11 at 07:36
  • 1
    FWIW the OP seems to require month first. – John Machin Oct 01 '11 at 07:39
  • @Jeff: Agreed, that's pretty good. – bobince Oct 01 '11 at 07:39
  • 2
    @John: Ah yes, looks like. In general I'd strongly advise against using this date format for exactly this reason, locale-dependent confusion. Please use the ISO 8601 format (`%Y-%m-%d`) wherever possible as it is the only unambiguous ordering. – bobince Oct 01 '11 at 07:41
  • @bobince: Absolutely! YYYY-MM-DD makes sense. Even DD-MM-YYYY or DD/MM/YYYY isn't too silly, though it makes useful sorting harder. But M/D/YYYY which the Americans use is just plain illogical. – Chris Morgan Oct 01 '11 at 07:47
  • @Jeff: Why not put that as an answer? – Chris Morgan Oct 01 '11 at 07:47
  • @ChrisMorgan: I was but bobince had already beat me to it. My solution was practically the same as his so there's no point in duplicating it. – Jeff Mercado Oct 01 '11 at 07:49
  • @Jeff: it's enough different that I think it's worth a separate answer. Then you get more votes, too (though being over 10k you perhaps don't care?) – Chris Morgan Oct 01 '11 at 07:50
1

The datetime object has a method strftime(). This would give you more flexibility to use the in-built format strings.

http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior.

I have used lstrip('0') to remove the leading zero.

>>> d = datetime.datetime(1982, 1, 27)

>>> d.strftime("%m/%d/%y")
'01/27/82'

>>> d.strftime("%m/%d/%Y")
'01/27/1982'

>>> d.strftime("%m/%d/%Y").lstrip('0')
'1/27/1982'
varunl
  • 19,499
  • 5
  • 29
  • 47