2

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

?

1
  • Use datetime.strftime for formatting timestamps Commented Nov 24, 2011 at 11:35

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Advanced string formatting of datetime objects uses strftime, so you can also use "{0:%Y%m%d%H%M}".format(now).
@eryksun: Interesting, wasn't aware of that.
For CPython 2.x, it's on the last line of the date_format function in datetimemodule.c.
4

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.

Further information:

1 Comment

+1; a good explanation of the %02d (even if it's still the wrong tool for the job :P).
1

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.

Comments

1
now = datetime.datetime.now()
print "%d%02d%02d%02d%02d" % (now.year, now.month, now.day, now.hour, now.minute)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.