patternpythonMinor
Python Long UTC DateTime String
Viewed 0 times
utclongpythonstringdatetime
Problem
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))Solution
Maybe, this is marginally cleaner, based on @Gareth's comment:
The not so great part is treating
The advantage of this way over the original is instead of 2 calls to
'{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.Code Snippets
'{0:%d} {0:%b} {0:%Y} {0:%I}:{0:%M}:{0:%S}.{1:03d} {0:%p}'.format(now, now.microsecond // 1000)Context
StackExchange Code Review Q#63775, answer score: 2
Revisions (0)
No revisions yet.