I have a simple script:
now = datetime.datetime.now()
print "%d%d%d%d%d" % ( now.year, now.month, now.day, now.hour, now.minute )
result:
20111124149
How to get result:
201111241409
?
I have a simple script:
now = datetime.datetime.now()
print "%d%d%d%d%d" % ( now.year, now.month, now.day, now.hour, now.minute )
result:
20111124149
How to get result:
201111241409
?
Method one: use %02d instead of %d. This pads up to width two with leading zeros.
print "%02d%02d%02d%02d%02d" % (now.year, now.month, now.day, now.hour, now.minute)
Method two, the correct way: use datetime.strftime.
print now.strftime('%Y%m%d%H%M')
For explanation of the format string, see strftime() and strptime() Behavior in the Python docs.
datetime objects uses strftime, so you can also use "{0:%Y%m%d%H%M}".format(now).Specify that the numbers should have width two and be zero-padded:
now = datetime.datetime.now()
print "%04d%02d%02d%02d%02d" % ( now.year, now.month, now.day, now.hour, now.minute )
If we break one of the components down, we get:
% marks the start of a substitution target.0 makes the result zero-padded.2 means, that the result should be 2 characters wide.d means that it's a decimal value.%02d (even if it's still the wrong tool for the job :P).I'd suggest this approach:
print "{0:02d}{1:02d}{2:02d}{3:02d}{4:02d}".format(now.year, now.month, now.day,
now.hour, now.minute)
The format-method should be preferred over the old formatting syntax. You can find more information on how to write the formatting-string here.