# Python Long UTC DateTime String

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


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.

• The heck, that actually works? I love it! I didn’t know that you could use strftime-formatters inside .format. – Jonas Schäfer Sep 26 '14 at 10:41
• To pad with zeros when millisecond < 100000. If you don't need fixed length always then you can simplify – Stop ongoing harm to Monica Sep 26 '14 at 12:16
• I updated my post. // was unnecessary, / is enough, because now.microsecond and 1000 are both integers, so the division will give an integer – Stop ongoing harm to Monica Sep 26 '14 at 12:32
• @janos Only in python2 and without from __future__ import division. Don’t rely on it for the sake of upward compatibility. – Jonas Schäfer Sep 26 '14 at 13:36
• 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. – Stop ongoing harm to Monica Sep 26 '14 at 13:41