Reputation: 221
I am trying to use datetime objects, including datetime.month
, datetime.day
, and datetime.hour
.
The problem is that these objects (say datetime.month
) give values as 1, 2, 3, and so on to 12. Instead, I need these in the format 01,02,03 and so on to 12. There's a similar issue with days and months.
How can I switch to this format?
I realized this wasn't a very clear question:
I'm using string formatting to print values from a dictionary I have with timestamps.
So, the expression is roughly:
print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) )
My values were originally in the correct "%Y-%m-%d
form (such as 2000-01-01). Using the above, I get 2000-1-1.
Upvotes: 14
Views: 21500
Reputation: 31
Wiki: https://www.w3schools.com/python/python_datetime.asp
You can check the strftime() method. Look this out:
from datetime import datetime
today = datetime.today()
print(today.strftime("%Y%m%d")) # yyyyMMdd
Upvotes: 0
Reputation: 5181
zfill is easier to remember:
In [19]: str(dt.month).zfill(2)
Out[19]: '07'
Upvotes: 2
Reputation: 309889
You can print the individual attributes using string formatting:
print ('%02d' % (mydate.month))
Or more recent string formatting (introduced in python 2.6):
print ('{0:02d}'.format(a.month)) # python 2.7+ -- '{:02d}' will work
Note that even:
print ('{0:%m}'.format(a)) # python 2.7+ -- '{:%m}' will work.
will work.
or alternatively using the strftime method of datetime objects:
print (mydate.strftime('%m'))
And just for the sake of completeness:
print (mydate.strftime('%Y-%m-%d'))
will nicely replace the code in your edit.
Upvotes: 32
Reputation: 15198
You can convert them to strings and simply pad them:
import datetime
d = datetime.datetime(2012, 5, 25)
m = str(d.month).rjust(2, '0')
print(m) # Outputs "05"
Or you could just a str.format
:
import datetime
d = datetime.datetime(2012, 5, 25)
print("{:0>2}".format(d.month))
EDIT: To answer the updated question, have you tried this?
import datetime
d = datetime.datetime(2012, 5, 25)
print("{:0>4}-{:0>2}-{:0>2}".format(d.year, d.month, d.day))
You said you were originally printing them using string formatting, so what did you change? This code:
print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) )
Doesn't really make any sense, since I'm a little unclear as to what arguments you are passing in. I assume just date.year
, date.month
, and date.day
, but it's unclear. What action are you performing with len(str)
?
Upvotes: 1