Format of datetime objects

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 ​​like 1, 2, 3 and so on 12. Instead, I need them in the format 01.02.03 and so on to 12. There is a similar problem with days and months.

How can I switch to this format?


I realized that this was not a very clear question:

I use string formatting to print values ​​from a dictionary that I have with timestamps.

So, unloading is approximately equal to:

print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) ) |

My values ​​were originally in the correct form "%Y-%m-%d (for example, 2000-01-01). Using the above, I get 2000-1-1.

+6
source share
2 answers

You can print individual attributes using line formatting:

 print ('%02d' % (mydate.month)) 

Or later string formatting (introduced in python 2.6):

 print ('{0:02d}'.format(a.month)) # python 2.7+ -- '{:02d}' will work 

Please 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')) 

beautifully replace the code in your editing.

+21
source

You can convert them to strings and just lay them out:

 import datetime d = datetime.datetime(2012, 5, 25) m = str(d.month).rjust(2, '0') print(m) # Outputs "05" 

Or you can just 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 to do 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 originally printed them using line formatting, so what did you change? This code:

 print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) ) 

It makes no sense, as I'm a little unclear as to which arguments you pass. I assume it is just date.year , date.month and date.day , but this is unclear. What action do you perform with len(str) ?

+2
source

Source: https://habr.com/ru/post/921235/


All Articles