8
Using django.utils.dateformat
which Steven linked to:
>>> import datetime
>>> from django.utils import dateformat
>>> dateformat.format(datetime.datetime.now(), 'F j, Y, P')
u'April 14, 2012, 1:31 p.m.'
P
is the interesting extension to strftime
, on line 93:
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension.
1
Here’s one lazy way to do it:
def f(dt):
s = dt.strftime('%B %d, %Y, %I:%M %p')
for unwanted, wanted in [
('12:00 AM', 'midnight'),
('12:00 PM', 'noon'),
('AM','a.m.'),
('PM', 'p.m.'),
(':00', ''),
(' 0', ' ')]:
s = s.replace(unwanted, wanted)
return s
This
print f(datetime(2012, 4, 4, 6))
print f(datetime(2012, 4, 14, 12, 6))
print f(datetime(2012, 4, 14, 12))
print f(datetime(2012, 4, 14, 0))
print f(datetime(2012, 4, 14, 6, 2))
gives
April 4, 2012, 6 a.m.
April 14, 2012, 12:06 p.m.
April 14, 2012, noon
April 14, 2012, midnight
April 14, 2012, 6:02 a.m.
- [Django]-Celery: running a worker with superuser privileges
- [Django]-Nginx/gunicorn connection hanging for 60 seconds
- [Django]-Why does manage.py execution script run twice when using it under if __name__ == "__main__"
- [Django]-Testing Django project, how can I avoid Errno 10054?
Source:stackexchange.com