1

In python how would I format the date as 1/1/1990?

dayToday = datetime.date(1990,1,1) print dayToday

This returns 1990-01-01, but I want it to look like 1/1/1990. (Jan 1 1990)

lebout
  • 85
  • 1
  • 10
  • that is how sane people store their dates. :) – Amelia Apr 19 '13 at 04:28
  • 1
    @MattBall Not a duplicate if OP cares about leading `0`. – timss Apr 19 '13 at 04:42
  • @mgilson Combined, it's a duplicate, but I'm not sure it's applicable when neither of those answers OP separately on both how to format from a date, and to fix leading `0`. Flag it if you feel like it. – timss Apr 19 '13 at 04:51

4 Answers4

1

Try to look into python datetime.strftime

dayToday = datetime.date(1990,1,1) 
print dayToday.strftime('%Y/%m/%d')
>>> 1990/01/01
print dayToday.strftime('%Y/%b/%d')
>>> 1990/Jan/01
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
0

Use the datetime.strftime function with an appropriate format string:

>>> now = datetime.datetime.now()
>>> print now.strftime('%Y/%m/%d')
2013/04/19
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
0

Others have showed how to get the output 1990/01/01, but assuming you don't want the leading zeros in there, the only way that I know of to do it is to do the string formatting yourself:

>>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = dt.datetime.now())
'2013/4/19'
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

With the correct format and a without leading 0:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%-m/%-d/%Y")
'4/19/2013'

Reported to only work for Linux, but I haven't tested anything else personally.
Tested and working for 2.7.3 and 3.2.3 on Linux x64.

Community
  • 1
  • 1
timss
  • 9,982
  • 4
  • 34
  • 56
  • Are you sure? This gives me: `'-m/-d/2013'`. Maybe platform specific? (I'm using OS-X) – mgilson Apr 19 '13 at 04:33
  • @mgilson It seems it's a Linux-only. – timss Apr 19 '13 at 04:38
  • Tested on my linux machine and it works there. Which makes me feel good. I was trying stuff like this before I finally came up with the answer I did and none of it worked. Now I know why :) – mgilson Apr 19 '13 at 04:38