3
\$\begingroup\$
now = datetime.datetime.utcnow()
now.strftime('%d %b %Y %I:%M:%S.%f')[:-3] + now.strftime(' %p')

Is there a cleaner solution for this? I don't want the extra 000 to appear everytime in %f.

EDIT: Got some more possible combinations:

now.strftime('%d %b %Y %I:%M:%S.%f')[:-3] + (' PM' if now.hour > 11 else ' AM')
now.strftime('%d %b %Y %I:%M:%S.X %p').replace('X', str(now.microsecond / 1000))
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Maybe, this is marginally cleaner, based on @Gareth's comment:

'{0:%d} {0:%b} {0:%Y} {0:%I}:{0:%M}:{0:%S}.{1:03d} {0:%p}'.format(now, now.microsecond // 1000)

The not so great part is treating now.microseconds differently from the rest. But since the vale is an integer in the range 0..999999, and you want the value divided by 1000, I don't see a way around. For example if the value is 12345, you would want to get 012. Padding with zeros is easy, once the number is divided by 1000. Or you could pad with zeros up to 6 digits and take the first 3 characters, but I couldn't find a formatting exceptions to do that.

The advantage of this way over the original is instead of 2 calls to strftime and a string concatenation and a string slicing, there's now a single .format call.

\$\endgroup\$
5
  • \$\begingroup\$ The heck, that actually works? I love it! I didn’t know that you could use strftime-formatters inside .format. \$\endgroup\$ Sep 26, 2014 at 10:41
  • \$\begingroup\$ To pad with zeros when millisecond < 100000. If you don't need fixed length always then you can simplify \$\endgroup\$
    – janos
    Sep 26, 2014 at 12:16
  • \$\begingroup\$ I updated my post. // was unnecessary, / is enough, because now.microsecond and 1000 are both integers, so the division will give an integer \$\endgroup\$
    – janos
    Sep 26, 2014 at 12:32
  • 1
    \$\begingroup\$ @janos Only in python2 and without from __future__ import division. Don’t rely on it for the sake of upward compatibility. \$\endgroup\$ Sep 26, 2014 at 13:36
  • \$\begingroup\$ Dammit. I knew I had a good reason for // in the first place. Thanks @JonasWielicki, I put it back. So in Python 3 division between integers results in float. Using // works as expected in both Python 2 and 3. \$\endgroup\$
    – janos
    Sep 26, 2014 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.