Convert Date To Natural Language In Python?
Solution 1:
The Babel project offers a full-featured date and time localization library.
You'll also need the iso8601
module to parse a date-time string with a timezone correctly.
It either formats dates and times based on locale:
>>> from datetime import date, datetime, time
>>> from babel.dates import format_date, format_datetime, format_time
>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en')
u'Apr 1, 2007'>>> format_date(d, locale='de_DE')
u'01.04.2007'
or it let's you specify the format in detail. This includes formatting the timezone.
Putting the parser and the formatter together:
>>> dt = iso8601.parse_date("2012-08-25T02:00:00Z")
>>> format_date(dt, "MMMM dd, yyyy", locale='en') + ' at ' + format_time(dt, "HH:mm V")
u'August 25, 2012 at 02:00 World (GMT) Time'
Ordinals ('1st', '2nd', etc.) are a little harder to do internationally, and the LDML format used by Babel doesn't include a pattern for these.
If you must have an ordinal in your date formatting (perhaps because you only expect to output in English), you'll have to create those yourself:
>>> suffix = ('st'if dt.day in [1,21,31]
... else'nd'if dt.day in [2, 22]
... else'rd'if dt.day in [3, 23]
... else'th')
>>> u'{date}{suffix}, {year} at {time}'.format(
... date=format_date(dt, "MMMM dd", locale='en'),
... suffix=suffix, year=dt.year,
... time=format_time(dt, "HH:mm V"))
u'August 25th, 2012 at 02:00 World (GMT) Time'
Solution 2:
You can get a custom string representation of your date using the strftime()
method. strftime accepts a string pattern explaining how you want to format your date.
For example:
print today.strftime('We are the %d, %h %Y')
'We are the 22, Nov 2008'
All the letters after a "%" represent a format for something:
- %d is the day number
- %m is the month number
- %y is the year last two digits
- %Y is the all year
Solution 3:
Not 100% the answer to your question, but this code might help you starting formatting time and date:
import datetime
print datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S')
Solution 4:
defmyFormat(dtime):
if dtime.day in [1,21,31] : ending = "st"elif dtime.day in [2,22] : ending = "nd"elif dtime.day in [3,23] : ending = "rd"else : ending = "th"return dtime.strftime("%B %d"+ ending + " of %Y")
Post a Comment for "Convert Date To Natural Language In Python?"