| | 67 | It is tempting to use Python stdlib's `strftime()` each time we want to convert a `datetime` to a string. However, this function uses the currently set locale by default (process-specific), which is not thread safe. Babel provides a `format_datetime` function that works more or less the same way and can take a locale as parameter. We put a wrapper around it so that it takes the currently defined (thread-specific) Indico locale, making things easier for everyone. |
| | 68 | |
| | 69 | {{{ |
| | 70 | #!python |
| | 71 | >>> from indico.util.date_time import format_datetime, now_utc |
| | 72 | |
| | 73 | >>> format_datetime(now_utc()) |
| | 74 | '28 Jul 2011 12:38:03' |
| | 75 | |
| | 76 | >>> format_datetime(now_utc(), locale="fr_FR") |
| | 77 | '28 juil. 2011 12:39:23' |
| | 78 | |
| | 79 | >>> format_datetime(now_utc(), locale="fr_FR", format="long", timezone='Europe/Zurich') |
| | 80 | '28 juillet 2011 12:40:05 +0000' |
| | 81 | }}} |
| | 82 | |
| | 83 | Timezones are also supported: |
| | 84 | |
| | 85 | {{{ |
| | 86 | #!python |
| | 87 | >>> from pytz import timezone |
| | 88 | >>> format_datetime(now_utc(), locale='pt_PT', format='full', timezone=timezone('Europe/Zurich')) |
| | 89 | 'quinta-feira, 28 de Julho de 2011 14H45m18s Horário Suíça' |
| | 90 | }}} |
| | 91 | |
| | 92 | Custom formats may be specified using [http://babel.edgewall.org/wiki/Documentation/dates.html#pattern-syntax LDML]: |
| | 93 | |
| | 94 | {{{ |
| | 95 | #!python |
| | 96 | >>> format_datetime(now_utc(), locale='es_ES', format='yyyy G') |
| | 97 | '2011 d.C.' |
| | 98 | }}} |
| | 99 | |
| | 100 | More information can be found at [http://babel.edgewall.org/wiki/Documentation/dates.html Babel's docs on Date Formatting]. |
| | 101 | |