dates.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2007 Edgewall Software
  4. # All rights reserved.
  5. #
  6. # This software is licensed as described in the file COPYING, which
  7. # you should have received as part of this distribution. The terms
  8. # are also available at http://babel.edgewall.org/wiki/License.
  9. #
  10. # This software consists of voluntary contributions made by many
  11. # individuals. For the exact contribution history, see the revision
  12. # history and logs, available at http://babel.edgewall.org/log/.
  13. """Locale dependent formatting and parsing of dates and times.
  14. The default locale for the functions in this module is determined by the
  15. following environment variables, in that order:
  16. * ``LC_TIME``,
  17. * ``LC_ALL``, and
  18. * ``LANG``
  19. """
  20. from datetime import date, datetime, time, timedelta, tzinfo
  21. import re
  22. from babel.core import default_locale, get_global, Locale
  23. from babel.util import UTC
  24. __all__ = ['format_date', 'format_datetime', 'format_time',
  25. 'get_timezone_name', 'parse_date', 'parse_datetime', 'parse_time']
  26. __docformat__ = 'restructuredtext en'
  27. LC_TIME = default_locale('LC_TIME')
  28. # Aliases for use in scopes where the modules are shadowed by local variables
  29. date_ = date
  30. datetime_ = datetime
  31. time_ = time
  32. def get_period_names(locale=LC_TIME):
  33. """Return the names for day periods (AM/PM) used by the locale.
  34. >>> get_period_names(locale='en_US')['am']
  35. u'AM'
  36. :param locale: the `Locale` object, or a locale string
  37. :return: the dictionary of period names
  38. :rtype: `dict`
  39. """
  40. return Locale.parse(locale).periods
  41. def get_day_names(width='wide', context='format', locale=LC_TIME):
  42. """Return the day names used by the locale for the specified format.
  43. >>> get_day_names('wide', locale='en_US')[1]
  44. u'Tuesday'
  45. >>> get_day_names('abbreviated', locale='es')[1]
  46. u'mar'
  47. >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
  48. u'D'
  49. :param width: the width to use, one of "wide", "abbreviated", or "narrow"
  50. :param context: the context, either "format" or "stand-alone"
  51. :param locale: the `Locale` object, or a locale string
  52. :return: the dictionary of day names
  53. :rtype: `dict`
  54. """
  55. return Locale.parse(locale).days[context][width]
  56. def get_month_names(width='wide', context='format', locale=LC_TIME):
  57. """Return the month names used by the locale for the specified format.
  58. >>> get_month_names('wide', locale='en_US')[1]
  59. u'January'
  60. >>> get_month_names('abbreviated', locale='es')[1]
  61. u'ene'
  62. >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
  63. u'J'
  64. :param width: the width to use, one of "wide", "abbreviated", or "narrow"
  65. :param context: the context, either "format" or "stand-alone"
  66. :param locale: the `Locale` object, or a locale string
  67. :return: the dictionary of month names
  68. :rtype: `dict`
  69. """
  70. return Locale.parse(locale).months[context][width]
  71. def get_quarter_names(width='wide', context='format', locale=LC_TIME):
  72. """Return the quarter names used by the locale for the specified format.
  73. >>> get_quarter_names('wide', locale='en_US')[1]
  74. u'1st quarter'
  75. >>> get_quarter_names('abbreviated', locale='de_DE')[1]
  76. u'Q1'
  77. :param width: the width to use, one of "wide", "abbreviated", or "narrow"
  78. :param context: the context, either "format" or "stand-alone"
  79. :param locale: the `Locale` object, or a locale string
  80. :return: the dictionary of quarter names
  81. :rtype: `dict`
  82. """
  83. return Locale.parse(locale).quarters[context][width]
  84. def get_era_names(width='wide', locale=LC_TIME):
  85. """Return the era names used by the locale for the specified format.
  86. >>> get_era_names('wide', locale='en_US')[1]
  87. u'Anno Domini'
  88. >>> get_era_names('abbreviated', locale='de_DE')[1]
  89. u'n. Chr.'
  90. :param width: the width to use, either "wide", "abbreviated", or "narrow"
  91. :param locale: the `Locale` object, or a locale string
  92. :return: the dictionary of era names
  93. :rtype: `dict`
  94. """
  95. return Locale.parse(locale).eras[width]
  96. def get_date_format(format='medium', locale=LC_TIME):
  97. """Return the date formatting patterns used by the locale for the specified
  98. format.
  99. >>> get_date_format(locale='en_US')
  100. <DateTimePattern u'MMM d, yyyy'>
  101. >>> get_date_format('full', locale='de_DE')
  102. <DateTimePattern u'EEEE, d. MMMM yyyy'>
  103. :param format: the format to use, one of "full", "long", "medium", or
  104. "short"
  105. :param locale: the `Locale` object, or a locale string
  106. :return: the date format pattern
  107. :rtype: `DateTimePattern`
  108. """
  109. return Locale.parse(locale).date_formats[format]
  110. def get_datetime_format(format='medium', locale=LC_TIME):
  111. """Return the datetime formatting patterns used by the locale for the
  112. specified format.
  113. >>> get_datetime_format(locale='en_US')
  114. u'{1} {0}'
  115. :param format: the format to use, one of "full", "long", "medium", or
  116. "short"
  117. :param locale: the `Locale` object, or a locale string
  118. :return: the datetime format pattern
  119. :rtype: `unicode`
  120. """
  121. patterns = Locale.parse(locale).datetime_formats
  122. if format not in patterns:
  123. format = None
  124. return patterns[format]
  125. def get_time_format(format='medium', locale=LC_TIME):
  126. """Return the time formatting patterns used by the locale for the specified
  127. format.
  128. >>> get_time_format(locale='en_US')
  129. <DateTimePattern u'h:mm:ss a'>
  130. >>> get_time_format('full', locale='de_DE')
  131. <DateTimePattern u'HH:mm:ss v'>
  132. :param format: the format to use, one of "full", "long", "medium", or
  133. "short"
  134. :param locale: the `Locale` object, or a locale string
  135. :return: the time format pattern
  136. :rtype: `DateTimePattern`
  137. """
  138. return Locale.parse(locale).time_formats[format]
  139. def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
  140. """Return the timezone associated with the given `datetime` object formatted
  141. as string indicating the offset from GMT.
  142. >>> dt = datetime(2007, 4, 1, 15, 30)
  143. >>> get_timezone_gmt(dt, locale='en')
  144. u'GMT+00:00'
  145. >>> from pytz import timezone
  146. >>> tz = timezone('America/Los_Angeles')
  147. >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz)
  148. >>> get_timezone_gmt(dt, locale='en')
  149. u'GMT-08:00'
  150. >>> get_timezone_gmt(dt, 'short', locale='en')
  151. u'-0800'
  152. The long format depends on the locale, for example in France the acronym
  153. UTC string is used instead of GMT:
  154. >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
  155. u'UTC-08:00'
  156. :param datetime: the ``datetime`` object; if `None`, the current date and
  157. time in UTC is used
  158. :param width: either "long" or "short"
  159. :param locale: the `Locale` object, or a locale string
  160. :return: the GMT offset representation of the timezone
  161. :rtype: `unicode`
  162. :since: version 0.9
  163. """
  164. if datetime is None:
  165. datetime = datetime_.utcnow()
  166. elif isinstance(datetime, (int, long)):
  167. datetime = datetime_.utcfromtimestamp(datetime).time()
  168. if datetime.tzinfo is None:
  169. datetime = datetime.replace(tzinfo=UTC)
  170. locale = Locale.parse(locale)
  171. offset = datetime.tzinfo.utcoffset(datetime)
  172. seconds = offset.days * 24 * 60 * 60 + offset.seconds
  173. hours, seconds = divmod(seconds, 3600)
  174. if width == 'short':
  175. pattern = u'%+03d%02d'
  176. else:
  177. pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
  178. return pattern % (hours, seconds // 60)
  179. def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME):
  180. """Return a representation of the given timezone using "location format".
  181. The result depends on both the local display name of the country and the
  182. city associated with the time zone:
  183. >>> from pytz import timezone
  184. >>> tz = timezone('America/St_Johns')
  185. >>> get_timezone_location(tz, locale='de_DE')
  186. u"Kanada (St. John's)"
  187. >>> tz = timezone('America/Mexico_City')
  188. >>> get_timezone_location(tz, locale='de_DE')
  189. u'Mexiko (Mexiko-Stadt)'
  190. If the timezone is associated with a country that uses only a single
  191. timezone, just the localized country name is returned:
  192. >>> tz = timezone('Europe/Berlin')
  193. >>> get_timezone_name(tz, locale='de_DE')
  194. u'Deutschland'
  195. :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
  196. the timezone; if `None`, the current date and time in
  197. UTC is assumed
  198. :param locale: the `Locale` object, or a locale string
  199. :return: the localized timezone name using location format
  200. :rtype: `unicode`
  201. :since: version 0.9
  202. """
  203. if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)):
  204. dt = None
  205. tzinfo = UTC
  206. elif isinstance(dt_or_tzinfo, (datetime, time)):
  207. dt = dt_or_tzinfo
  208. if dt.tzinfo is not None:
  209. tzinfo = dt.tzinfo
  210. else:
  211. tzinfo = UTC
  212. else:
  213. dt = None
  214. tzinfo = dt_or_tzinfo
  215. locale = Locale.parse(locale)
  216. if hasattr(tzinfo, 'zone'):
  217. zone = tzinfo.zone
  218. else:
  219. zone = tzinfo.tzname(dt or datetime.utcnow())
  220. # Get the canonical time-zone code
  221. zone = get_global('zone_aliases').get(zone, zone)
  222. info = locale.time_zones.get(zone, {})
  223. # Otherwise, if there is only one timezone for the country, return the
  224. # localized country name
  225. region_format = locale.zone_formats['region']
  226. territory = get_global('zone_territories').get(zone)
  227. if territory not in locale.territories:
  228. territory = 'ZZ' # invalid/unknown
  229. territory_name = locale.territories[territory]
  230. if territory and len(get_global('territory_zones').get(territory, [])) == 1:
  231. return region_format % (territory_name)
  232. # Otherwise, include the city in the output
  233. fallback_format = locale.zone_formats['fallback']
  234. if 'city' in info:
  235. city_name = info['city']
  236. else:
  237. metazone = get_global('meta_zones').get(zone)
  238. metazone_info = locale.meta_zones.get(metazone, {})
  239. if 'city' in metazone_info:
  240. city_name = metainfo['city']
  241. elif '/' in zone:
  242. city_name = zone.split('/', 1)[1].replace('_', ' ')
  243. else:
  244. city_name = zone.replace('_', ' ')
  245. return region_format % (fallback_format % {
  246. '0': city_name,
  247. '1': territory_name
  248. })
  249. def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False,
  250. locale=LC_TIME):
  251. r"""Return the localized display name for the given timezone. The timezone
  252. may be specified using a ``datetime`` or `tzinfo` object.
  253. >>> from pytz import timezone
  254. >>> dt = time(15, 30, tzinfo=timezone('America/Los_Angeles'))
  255. >>> get_timezone_name(dt, locale='en_US')
  256. u'Pacific Standard Time'
  257. >>> get_timezone_name(dt, width='short', locale='en_US')
  258. u'PST'
  259. If this function gets passed only a `tzinfo` object and no concrete
  260. `datetime`, the returned display name is indenpendent of daylight savings
  261. time. This can be used for example for selecting timezones, or to set the
  262. time of events that recur across DST changes:
  263. >>> tz = timezone('America/Los_Angeles')
  264. >>> get_timezone_name(tz, locale='en_US')
  265. u'Pacific Time'
  266. >>> get_timezone_name(tz, 'short', locale='en_US')
  267. u'PT'
  268. If no localized display name for the timezone is available, and the timezone
  269. is associated with a country that uses only a single timezone, the name of
  270. that country is returned, formatted according to the locale:
  271. >>> tz = timezone('Europe/Berlin')
  272. >>> get_timezone_name(tz, locale='de_DE')
  273. u'Deutschland'
  274. >>> get_timezone_name(tz, locale='pt_BR')
  275. u'Hor\xe1rio Alemanha'
  276. On the other hand, if the country uses multiple timezones, the city is also
  277. included in the representation:
  278. >>> tz = timezone('America/St_Johns')
  279. >>> get_timezone_name(tz, locale='de_DE')
  280. u"Kanada (St. John's)"
  281. The `uncommon` parameter can be set to `True` to enable the use of timezone
  282. representations that are not commonly used by the requested locale. For
  283. example, while in French the central European timezone is usually
  284. abbreviated as "HEC", in Canadian French, this abbreviation is not in
  285. common use, so a generic name would be chosen by default:
  286. >>> tz = timezone('Europe/Paris')
  287. >>> get_timezone_name(tz, 'short', locale='fr_CA')
  288. u'France'
  289. >>> get_timezone_name(tz, 'short', uncommon=True, locale='fr_CA')
  290. u'HEC'
  291. :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
  292. the timezone; if a ``tzinfo`` object is used, the
  293. resulting display name will be generic, i.e.
  294. independent of daylight savings time; if `None`, the
  295. current date in UTC is assumed
  296. :param width: either "long" or "short"
  297. :param uncommon: whether even uncommon timezone abbreviations should be used
  298. :param locale: the `Locale` object, or a locale string
  299. :return: the timezone display name
  300. :rtype: `unicode`
  301. :since: version 0.9
  302. :see: `LDML Appendix J: Time Zone Display Names
  303. <http://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_
  304. """
  305. if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)):
  306. dt = None
  307. tzinfo = UTC
  308. elif isinstance(dt_or_tzinfo, (datetime, time)):
  309. dt = dt_or_tzinfo
  310. if dt.tzinfo is not None:
  311. tzinfo = dt.tzinfo
  312. else:
  313. tzinfo = UTC
  314. else:
  315. dt = None
  316. tzinfo = dt_or_tzinfo
  317. locale = Locale.parse(locale)
  318. if hasattr(tzinfo, 'zone'):
  319. zone = tzinfo.zone
  320. else:
  321. zone = tzinfo.tzname(dt)
  322. # Get the canonical time-zone code
  323. zone = get_global('zone_aliases').get(zone, zone)
  324. info = locale.time_zones.get(zone, {})
  325. # Try explicitly translated zone names first
  326. if width in info:
  327. if dt is None:
  328. field = 'generic'
  329. else:
  330. dst = tzinfo.dst(dt)
  331. if dst is None:
  332. field = 'generic'
  333. elif dst == 0:
  334. field = 'standard'
  335. else:
  336. field = 'daylight'
  337. if field in info[width]:
  338. return info[width][field]
  339. metazone = get_global('meta_zones').get(zone)
  340. if metazone:
  341. metazone_info = locale.meta_zones.get(metazone, {})
  342. if width in metazone_info and (uncommon or metazone_info.get('common')):
  343. if dt is None:
  344. field = 'generic'
  345. else:
  346. field = tzinfo.dst(dt) and 'daylight' or 'standard'
  347. if field in metazone_info[width]:
  348. return metazone_info[width][field]
  349. # If we have a concrete datetime, we assume that the result can't be
  350. # independent of daylight savings time, so we return the GMT offset
  351. if dt is not None:
  352. return get_timezone_gmt(dt, width=width, locale=locale)
  353. return get_timezone_location(dt_or_tzinfo, locale=locale)
  354. def format_date(date=None, format='medium', locale=LC_TIME):
  355. """Return a date formatted according to the given pattern.
  356. >>> d = date(2007, 04, 01)
  357. >>> format_date(d, locale='en_US')
  358. u'Apr 1, 2007'
  359. >>> format_date(d, format='full', locale='de_DE')
  360. u'Sonntag, 1. April 2007'
  361. If you don't want to use the locale default formats, you can specify a
  362. custom date pattern:
  363. >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
  364. u"Sun, Apr 1, '07"
  365. :param date: the ``date`` or ``datetime`` object; if `None`, the current
  366. date is used
  367. :param format: one of "full", "long", "medium", or "short", or a custom
  368. date/time pattern
  369. :param locale: a `Locale` object or a locale identifier
  370. :rtype: `unicode`
  371. :note: If the pattern contains time fields, an `AttributeError` will be
  372. raised when trying to apply the formatting. This is also true if
  373. the value of ``date`` parameter is actually a ``datetime`` object,
  374. as this function automatically converts that to a ``date``.
  375. """
  376. if date is None:
  377. date = date_.today()
  378. elif isinstance(date, datetime):
  379. date = date.date()
  380. locale = Locale.parse(locale)
  381. if format in ('full', 'long', 'medium', 'short'):
  382. format = get_date_format(format, locale=locale)
  383. pattern = parse_pattern(format)
  384. return pattern.apply(date, locale)
  385. def format_datetime(datetime=None, format='medium', tzinfo=None,
  386. locale=LC_TIME):
  387. """Return a date formatted according to the given pattern.
  388. >>> dt = datetime(2007, 04, 01, 15, 30)
  389. >>> format_datetime(dt, locale='en_US')
  390. u'Apr 1, 2007 3:30:00 PM'
  391. For any pattern requiring the display of the time-zone, the third-party
  392. ``pytz`` package is needed to explicitly specify the time-zone:
  393. >>> from pytz import timezone
  394. >>> format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'),
  395. ... locale='fr_FR')
  396. u'dimanche 1 avril 2007 17:30:00 HEC'
  397. >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
  398. ... tzinfo=timezone('US/Eastern'), locale='en')
  399. u'2007.04.01 AD at 11:30:00 EDT'
  400. :param datetime: the `datetime` object; if `None`, the current date and
  401. time is used
  402. :param format: one of "full", "long", "medium", or "short", or a custom
  403. date/time pattern
  404. :param tzinfo: the timezone to apply to the time for display
  405. :param locale: a `Locale` object or a locale identifier
  406. :rtype: `unicode`
  407. """
  408. if datetime is None:
  409. datetime = datetime_.utcnow()
  410. elif isinstance(datetime, (int, long)):
  411. datetime = datetime_.utcfromtimestamp(datetime)
  412. elif isinstance(datetime, time):
  413. datetime = datetime_.combine(date.today(), datetime)
  414. if datetime.tzinfo is None:
  415. datetime = datetime.replace(tzinfo=UTC)
  416. if tzinfo is not None:
  417. datetime = datetime.astimezone(tzinfo)
  418. if hasattr(tzinfo, 'normalize'): # pytz
  419. datetime = tzinfo.normalize(datetime)
  420. locale = Locale.parse(locale)
  421. if format in ('full', 'long', 'medium', 'short'):
  422. return get_datetime_format(format, locale=locale) \
  423. .replace('{0}', format_time(datetime, format, tzinfo=None,
  424. locale=locale)) \
  425. .replace('{1}', format_date(datetime, format, locale=locale))
  426. else:
  427. return parse_pattern(format).apply(datetime, locale)
  428. def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
  429. """Return a time formatted according to the given pattern.
  430. >>> t = time(15, 30)
  431. >>> format_time(t, locale='en_US')
  432. u'3:30:00 PM'
  433. >>> format_time(t, format='short', locale='de_DE')
  434. u'15:30'
  435. If you don't want to use the locale default formats, you can specify a
  436. custom time pattern:
  437. >>> format_time(t, "hh 'o''clock' a", locale='en')
  438. u"03 o'clock PM"
  439. For any pattern requiring the display of the time-zone, the third-party
  440. ``pytz`` package is needed to explicitly specify the time-zone:
  441. >>> from pytz import timezone
  442. >>> t = datetime(2007, 4, 1, 15, 30)
  443. >>> tzinfo = timezone('Europe/Paris')
  444. >>> t = tzinfo.localize(t)
  445. >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
  446. u'15:30:00 HEC'
  447. >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'),
  448. ... locale='en')
  449. u"09 o'clock AM, Eastern Daylight Time"
  450. As that example shows, when this function gets passed a
  451. ``datetime.datetime`` value, the actual time in the formatted string is
  452. adjusted to the timezone specified by the `tzinfo` parameter. If the
  453. ``datetime`` is "naive" (i.e. it has no associated timezone information),
  454. it is assumed to be in UTC.
  455. These timezone calculations are **not** performed if the value is of type
  456. ``datetime.time``, as without date information there's no way to determine
  457. what a given time would translate to in a different timezone without
  458. information about whether daylight savings time is in effect or not. This
  459. means that time values are left as-is, and the value of the `tzinfo`
  460. parameter is only used to display the timezone name if needed:
  461. >>> t = time(15, 30)
  462. >>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'),
  463. ... locale='fr_FR')
  464. u'15:30:00 HEC'
  465. >>> format_time(t, format='full', tzinfo=timezone('US/Eastern'),
  466. ... locale='en_US')
  467. u'3:30:00 PM ET'
  468. :param time: the ``time`` or ``datetime`` object; if `None`, the current
  469. time in UTC is used
  470. :param format: one of "full", "long", "medium", or "short", or a custom
  471. date/time pattern
  472. :param tzinfo: the time-zone to apply to the time for display
  473. :param locale: a `Locale` object or a locale identifier
  474. :rtype: `unicode`
  475. :note: If the pattern contains date fields, an `AttributeError` will be
  476. raised when trying to apply the formatting. This is also true if
  477. the value of ``time`` parameter is actually a ``datetime`` object,
  478. as this function automatically converts that to a ``time``.
  479. """
  480. if time is None:
  481. time = datetime.utcnow()
  482. elif isinstance(time, (int, long)):
  483. time = datetime.utcfromtimestamp(time)
  484. if time.tzinfo is None:
  485. time = time.replace(tzinfo=UTC)
  486. if isinstance(time, datetime):
  487. if tzinfo is not None:
  488. time = time.astimezone(tzinfo)
  489. if hasattr(tzinfo, 'normalize'): # pytz
  490. time = tzinfo.normalize(time)
  491. time = time.timetz()
  492. elif tzinfo is not None:
  493. time = time.replace(tzinfo=tzinfo)
  494. locale = Locale.parse(locale)
  495. if format in ('full', 'long', 'medium', 'short'):
  496. format = get_time_format(format, locale=locale)
  497. return parse_pattern(format).apply(time, locale)
  498. def parse_date(string, locale=LC_TIME):
  499. """Parse a date from a string.
  500. This function uses the date format for the locale as a hint to determine
  501. the order in which the date fields appear in the string.
  502. >>> parse_date('4/1/04', locale='en_US')
  503. datetime.date(2004, 4, 1)
  504. >>> parse_date('01.04.2004', locale='de_DE')
  505. datetime.date(2004, 4, 1)
  506. :param string: the string containing the date
  507. :param locale: a `Locale` object or a locale identifier
  508. :return: the parsed date
  509. :rtype: `date`
  510. """
  511. # TODO: try ISO format first?
  512. format = get_date_format(locale=locale).pattern.lower()
  513. year_idx = format.index('y')
  514. month_idx = format.index('m')
  515. if month_idx < 0:
  516. month_idx = format.index('l')
  517. day_idx = format.index('d')
  518. indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
  519. indexes.sort()
  520. indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
  521. # FIXME: this currently only supports numbers, but should also support month
  522. # names, both in the requested locale, and english
  523. numbers = re.findall('(\d+)', string)
  524. year = numbers[indexes['Y']]
  525. if len(year) == 2:
  526. year = 2000 + int(year)
  527. else:
  528. year = int(year)
  529. month = int(numbers[indexes['M']])
  530. day = int(numbers[indexes['D']])
  531. if month > 12:
  532. month, day = day, month
  533. return date(year, month, day)
  534. def parse_datetime(string, locale=LC_TIME):
  535. """Parse a date and time from a string.
  536. This function uses the date and time formats for the locale as a hint to
  537. determine the order in which the time fields appear in the string.
  538. :param string: the string containing the date and time
  539. :param locale: a `Locale` object or a locale identifier
  540. :return: the parsed date/time
  541. :rtype: `datetime`
  542. """
  543. raise NotImplementedError
  544. def parse_time(string, locale=LC_TIME):
  545. """Parse a time from a string.
  546. This function uses the time format for the locale as a hint to determine
  547. the order in which the time fields appear in the string.
  548. >>> parse_time('15:30:00', locale='en_US')
  549. datetime.time(15, 30)
  550. :param string: the string containing the time
  551. :param locale: a `Locale` object or a locale identifier
  552. :return: the parsed time
  553. :rtype: `time`
  554. """
  555. # TODO: try ISO format first?
  556. format = get_time_format(locale=locale).pattern.lower()
  557. hour_idx = format.index('h')
  558. if hour_idx < 0:
  559. hour_idx = format.index('k')
  560. min_idx = format.index('m')
  561. sec_idx = format.index('s')
  562. indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')]
  563. indexes.sort()
  564. indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
  565. # FIXME: support 12 hour clock, and 0-based hour specification
  566. # and seconds should be optional, maybe minutes too
  567. # oh, and time-zones, of course
  568. numbers = re.findall('(\d+)', string)
  569. hour = int(numbers[indexes['H']])
  570. minute = int(numbers[indexes['M']])
  571. second = int(numbers[indexes['S']])
  572. return time(hour, minute, second)
  573. class DateTimePattern(object):
  574. def __init__(self, pattern, format):
  575. self.pattern = pattern
  576. self.format = format
  577. def __repr__(self):
  578. return '<%s %r>' % (type(self).__name__, self.pattern)
  579. def __unicode__(self):
  580. return self.pattern
  581. def __mod__(self, other):
  582. assert type(other) is DateTimeFormat
  583. return self.format % other
  584. def apply(self, datetime, locale):
  585. return self % DateTimeFormat(datetime, locale)
  586. class DateTimeFormat(object):
  587. def __init__(self, value, locale):
  588. assert isinstance(value, (date, datetime, time))
  589. if isinstance(value, (datetime, time)) and value.tzinfo is None:
  590. value = value.replace(tzinfo=UTC)
  591. self.value = value
  592. self.locale = Locale.parse(locale)
  593. def __getitem__(self, name):
  594. char = name[0]
  595. num = len(name)
  596. if char == 'G':
  597. return self.format_era(char, num)
  598. elif char in ('y', 'Y', 'u'):
  599. return self.format_year(char, num)
  600. elif char in ('Q', 'q'):
  601. return self.format_quarter(char, num)
  602. elif char in ('M', 'L'):
  603. return self.format_month(char, num)
  604. elif char in ('w', 'W'):
  605. return self.format_week(char, num)
  606. elif char == 'd':
  607. return self.format(self.value.day, num)
  608. elif char == 'D':
  609. return self.format_day_of_year(num)
  610. elif char == 'F':
  611. return self.format_day_of_week_in_month()
  612. elif char in ('E', 'e', 'c'):
  613. return self.format_weekday(char, num)
  614. elif char == 'a':
  615. return self.format_period(char)
  616. elif char == 'h':
  617. if self.value.hour % 12 == 0:
  618. return self.format(12, num)
  619. else:
  620. return self.format(self.value.hour % 12, num)
  621. elif char == 'H':
  622. return self.format(self.value.hour, num)
  623. elif char == 'K':
  624. return self.format(self.value.hour % 12, num)
  625. elif char == 'k':
  626. if self.value.hour == 0:
  627. return self.format(24, num)
  628. else:
  629. return self.format(self.value.hour, num)
  630. elif char == 'm':
  631. return self.format(self.value.minute, num)
  632. elif char == 's':
  633. return self.format(self.value.second, num)
  634. elif char == 'S':
  635. return self.format_frac_seconds(num)
  636. elif char == 'A':
  637. return self.format_milliseconds_in_day(num)
  638. elif char in ('z', 'Z', 'v', 'V'):
  639. return self.format_timezone(char, num)
  640. else:
  641. raise KeyError('Unsupported date/time field %r' % char)
  642. def format_era(self, char, num):
  643. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)]
  644. era = int(self.value.year >= 0)
  645. return get_era_names(width, self.locale)[era]
  646. def format_year(self, char, num):
  647. value = self.value.year
  648. if char.isupper():
  649. week = self.get_week_number(self.get_day_of_year())
  650. if week == 0:
  651. value -= 1
  652. year = self.format(value, num)
  653. if num == 2:
  654. year = year[-2:]
  655. return year
  656. def format_quarter(self, char, num):
  657. quarter = (self.value.month - 1) // 3 + 1
  658. if num <= 2:
  659. return ('%%0%dd' % num) % quarter
  660. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
  661. context = {'Q': 'format', 'q': 'stand-alone'}[char]
  662. return get_quarter_names(width, context, self.locale)[quarter]
  663. def format_month(self, char, num):
  664. if num <= 2:
  665. return ('%%0%dd' % num) % self.value.month
  666. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
  667. context = {'M': 'format', 'L': 'stand-alone'}[char]
  668. return get_month_names(width, context, self.locale)[self.value.month]
  669. def format_week(self, char, num):
  670. if char.islower(): # week of year
  671. day_of_year = self.get_day_of_year()
  672. week = self.get_week_number(day_of_year)
  673. if week == 0:
  674. date = self.value - timedelta(days=day_of_year)
  675. week = self.get_week_number(self.get_day_of_year(date),
  676. date.weekday())
  677. return self.format(week, num)
  678. else: # week of month
  679. week = self.get_week_number(self.value.day)
  680. if week == 0:
  681. date = self.value - timedelta(days=self.value.day)
  682. week = self.get_week_number(date.day, date.weekday())
  683. pass
  684. return '%d' % week
  685. def format_weekday(self, char, num):
  686. if num < 3:
  687. if char.islower():
  688. value = 7 - self.locale.first_week_day + self.value.weekday()
  689. return self.format(value % 7 + 1, num)
  690. num = 3
  691. weekday = self.value.weekday()
  692. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
  693. context = {3: 'format', 4: 'format', 5: 'stand-alone'}[num]
  694. return get_day_names(width, context, self.locale)[weekday]
  695. def format_day_of_year(self, num):
  696. return self.format(self.get_day_of_year(), num)
  697. def format_day_of_week_in_month(self):
  698. return '%d' % ((self.value.day - 1) / 7 + 1)
  699. def format_period(self, char):
  700. period = {0: 'am', 1: 'pm'}[int(self.value.hour >= 12)]
  701. return get_period_names(locale=self.locale)[period]
  702. def format_frac_seconds(self, num):
  703. value = str(self.value.microsecond)
  704. return self.format(round(float('.%s' % value), num) * 10**num, num)
  705. def format_milliseconds_in_day(self, num):
  706. msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \
  707. self.value.minute * 60000 + self.value.hour * 3600000
  708. return self.format(msecs, num)
  709. def format_timezone(self, char, num):
  710. width = {3: 'short', 4: 'long'}[max(3, num)]
  711. if char == 'z':
  712. return get_timezone_name(self.value, width, locale=self.locale)
  713. elif char == 'Z':
  714. return get_timezone_gmt(self.value, width, locale=self.locale)
  715. elif char == 'v':
  716. return get_timezone_name(self.value.tzinfo, width,
  717. locale=self.locale)
  718. elif char == 'V':
  719. if num == 1:
  720. return get_timezone_name(self.value.tzinfo, width,
  721. uncommon=True, locale=self.locale)
  722. return get_timezone_location(self.value.tzinfo, locale=self.locale)
  723. def format(self, value, length):
  724. return ('%%0%dd' % length) % value
  725. def get_day_of_year(self, date=None):
  726. if date is None:
  727. date = self.value
  728. return (date - date_(date.year, 1, 1)).days + 1
  729. def get_week_number(self, day_of_period, day_of_week=None):
  730. """Return the number of the week of a day within a period. This may be
  731. the week number in a year or the week number in a month.
  732. Usually this will return a value equal to or greater than 1, but if the
  733. first week of the period is so short that it actually counts as the last
  734. week of the previous period, this function will return 0.
  735. >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
  736. >>> format.get_week_number(6)
  737. 1
  738. >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US'))
  739. >>> format.get_week_number(6)
  740. 2
  741. :param day_of_period: the number of the day in the period (usually
  742. either the day of month or the day of year)
  743. :param day_of_week: the week day; if ommitted, the week day of the
  744. current date is assumed
  745. """
  746. if day_of_week is None:
  747. day_of_week = self.value.weekday()
  748. first_day = (day_of_week - self.locale.first_week_day -
  749. day_of_period + 1) % 7
  750. if first_day < 0:
  751. first_day += 7
  752. week_number = (day_of_period + first_day - 1) / 7
  753. if 7 - first_day >= self.locale.min_week_days:
  754. week_number += 1
  755. return week_number
  756. PATTERN_CHARS = {
  757. 'G': [1, 2, 3, 4, 5], # era
  758. 'y': None, 'Y': None, 'u': None, # year
  759. 'Q': [1, 2, 3, 4], 'q': [1, 2, 3, 4], # quarter
  760. 'M': [1, 2, 3, 4, 5], 'L': [1, 2, 3, 4, 5], # month
  761. 'w': [1, 2], 'W': [1], # week
  762. 'd': [1, 2], 'D': [1, 2, 3], 'F': [1], 'g': None, # day
  763. 'E': [1, 2, 3, 4, 5], 'e': [1, 2, 3, 4, 5], 'c': [1, 3, 4, 5], # week day
  764. 'a': [1], # period
  765. 'h': [1, 2], 'H': [1, 2], 'K': [1, 2], 'k': [1, 2], # hour
  766. 'm': [1, 2], # minute
  767. 's': [1, 2], 'S': None, 'A': None, # second
  768. 'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4], 'v': [1, 4], 'V': [1, 4] # zone
  769. }
  770. def parse_pattern(pattern):
  771. """Parse date, time, and datetime format patterns.
  772. >>> parse_pattern("MMMMd").format
  773. u'%(MMMM)s%(d)s'
  774. >>> parse_pattern("MMM d, yyyy").format
  775. u'%(MMM)s %(d)s, %(yyyy)s'
  776. Pattern can contain literal strings in single quotes:
  777. >>> parse_pattern("H:mm' Uhr 'z").format
  778. u'%(H)s:%(mm)s Uhr %(z)s'
  779. An actual single quote can be used by using two adjacent single quote
  780. characters:
  781. >>> parse_pattern("hh' o''clock'").format
  782. u"%(hh)s o'clock"
  783. :param pattern: the formatting pattern to parse
  784. """
  785. if type(pattern) is DateTimePattern:
  786. return pattern
  787. result = []
  788. quotebuf = None
  789. charbuf = []
  790. fieldchar = ['']
  791. fieldnum = [0]
  792. def append_chars():
  793. result.append(''.join(charbuf).replace('%', '%%'))
  794. del charbuf[:]
  795. def append_field():
  796. limit = PATTERN_CHARS[fieldchar[0]]
  797. if limit and fieldnum[0] not in limit:
  798. raise ValueError('Invalid length for field: %r'
  799. % (fieldchar[0] * fieldnum[0]))
  800. result.append('%%(%s)s' % (fieldchar[0] * fieldnum[0]))
  801. fieldchar[0] = ''
  802. fieldnum[0] = 0
  803. for idx, char in enumerate(pattern.replace("''", '\0')):
  804. if quotebuf is None:
  805. if char == "'": # quote started
  806. if fieldchar[0]:
  807. append_field()
  808. elif charbuf:
  809. append_chars()
  810. quotebuf = []
  811. elif char in PATTERN_CHARS:
  812. if charbuf:
  813. append_chars()
  814. if char == fieldchar[0]:
  815. fieldnum[0] += 1
  816. else:
  817. if fieldchar[0]:
  818. append_field()
  819. fieldchar[0] = char
  820. fieldnum[0] = 1
  821. else:
  822. if fieldchar[0]:
  823. append_field()
  824. charbuf.append(char)
  825. elif quotebuf is not None:
  826. if char == "'": # end of quote
  827. charbuf.extend(quotebuf)
  828. quotebuf = None
  829. else: # inside quote
  830. quotebuf.append(char)
  831. if fieldchar[0]:
  832. append_field()
  833. elif charbuf:
  834. append_chars()
  835. return DateTimePattern(pattern, u''.join(result).replace('\0', "'"))