Reputation: 9501
I am trying to use datetime module. I need the month to come back as a INT with the ZERO in front. in the form as 01 for JAN, 02 for FEB etc etc. I can get 1 by using,
today = date.today()
m = today.month
I can get the correct format but not as an INT this way.
today.strftime("%m")
is there a simple way to get the desired format I need. I have looked in the reference and I am sure I am missing it, but could someone help.
Upvotes: 0
Views: 295
Reputation: 309929
'{:%m}'.format(datetime.datetime.now())
seems to work.
Of course, you could take the less direct approach:
'{:02d}'.format(datetime.datetime.now().month)
Or you could use old style string interpolation:
'%02d' % (datetime.datetime.now().month)
but I like the first one because I think it's cool ...
Finally, I don't see what is wrong with .strftime
... even though you said you tried it, it works just fine for me:
datetime.datetime.now().strftime('%m')
What it seems like you're looking for is a special subclass of int
which knows how to "represent" itself when it printed:
class MyInt(int):
def __str__(self):
return '%02d' % self
a = MyInt(3)
print (a)
However, I would definitely not recommend using this approach, instead I would recommend using string formatting or string interpolation as I've done above on the integer objects when you need to represent the integers as strings.
Upvotes: 5