module documentation

Locale dependent formatting and parsing of dates and times.

The default locale for the functions in this module is determined by the following environment variables, in that order:

  • LC_TIME,
  • LC_ALL, and
  • LANG
Unknown Field: copyright
  1. 2013-2021 by the Babel Team.
Unknown Field: license
BSD, see LICENSE for more details.
Function format​_date Return a date formatted according to the given pattern.
Function format​_datetime Return a date formatted according to the given pattern.
Function format​_interval Format an interval between two instants according to the locale's rules.
Function format​_skeleton Return a time and/or date formatted according to the given pattern.
Function format​_time Return a time formatted according to the given pattern.
Function format​_timedelta Return a time delta according to the rules of the given locale.
Function get​_date​_format Return the date formatting patterns used by the locale for the specified format.
Function get​_datetime​_format Return the datetime formatting patterns used by the locale for the specified format.
Function get​_day​_names Return the day names used by the locale for the specified format.
Function get​_era​_names Return the era names used by the locale for the specified format.
Function get​_month​_names Return the month names used by the locale for the specified format.
Function get​_next​_timezone​_transition No summary
Function get​_period​_names Return the names for day periods (AM/PM) used by the locale.
Function get​_quarter​_names Return the quarter names used by the locale for the specified format.
Function get​_time​_format Return the time formatting patterns used by the locale for the specified format.
Function get​_timezone Looks up a timezone by name and returns it. The timezone object returned comes from pytz and corresponds to the tzinfo interface and can be used with all of the functions of Babel that operate with dates.
Function get​_timezone​_gmt Return the timezone associated with the given datetime object formatted as string indicating the offset from GMT.
Function get​_timezone​_location Return a representation of the given timezone using "location format".
Function get​_timezone​_name Return the localized display name for the given timezone. The timezone may be specified using a datetime or tzinfo object.
Function parse​_date Parse a date from a string.
Function parse​_pattern Parse date, time, and datetime format patterns.
Function parse​_time Parse a time from a string.
Constant LC​_TIME Undocumented
Constant NO​_INHERITANCE​_MARKER Undocumented
Constant PATTERN​_CHAR​_ORDER Undocumented
Constant PATTERN​_CHARS Undocumented
Constant TIMEDELTA​_UNITS Undocumented
Class ​Date​Time​Format No class docstring; 0/2 instance variable, 3/18 methods documented
Class ​Date​Time​Pattern Undocumented
Class ​Timezone​Transition A helper object that represents the return value from get_next_timezone_transition.
Function ​_ensure​_datetime​_tzinfo Ensure the datetime passed has an attached tzinfo.
Function ​_format​_fallback​_interval Undocumented
Function ​_get​_datetime Get a datetime out of an "instant" (date, time, datetime, number).
Function ​_get​_dt​_and​_tzinfo Parse a dt_or_tzinfo value into a datetime and a tzinfo.
Function ​_get​_time Get a timezoned time from a given instant.
Function ​_get​_tz​_name Get the timezone name out of a time, datetime, or tzinfo object.
Function get​_period​_id Get the day period ID for a given time.
Function match​_skeleton Find the closest match for the given datetime skeleton among the options given.
Function split​_interval​_pattern Split an interval-describing datetime pattern into multiple pieces.
Function tokenize​_pattern Tokenize date format patterns.
Function untokenize​_pattern Turn a date format pattern token stream back into a string.
Variable ​_pattern​_cache Undocumented
def format_date(date=None, format='medium', locale=LC_TIME):

Return a date formatted according to the given pattern.

>>> d = date(2007, 4, 1)
>>> format_date(d, locale='en_US')
u'Apr 1, 2007'
>>> format_date(d, format='full', locale='de_DE')
u'Sonntag, 1. April 2007'

If you don't want to use the locale default formats, you can specify a custom date pattern:

>>> format_date(d, "EEE, MMM d, ''yy", locale='en')
u"Sun, Apr 1, '07"
Parameters
datethe date or datetime object; if None, the current date is used
formatone of "full", "long", "medium", or "short", or a custom date/time pattern
localea Locale object or a locale identifier
def format_datetime(datetime=None, format='medium', tzinfo=None, locale=LC_TIME):

Return a date formatted according to the given pattern.

>>> dt = datetime(2007, 4, 1, 15, 30)
>>> format_datetime(dt, locale='en_US')
u'Apr 1, 2007, 3:30:00 PM'

For any pattern requiring the display of the time-zone, the third-party pytz package is needed to explicitly specify the time-zone:

>>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
...                 locale='fr_FR')
u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
>>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
...                 tzinfo=get_timezone('US/Eastern'), locale='en')
u'2007.04.01 AD at 11:30:00 EDT'
Parameters
datetimethe datetime object; if None, the current date and time is used
formatone of "full", "long", "medium", or "short", or a custom date/time pattern
tzinfothe timezone to apply to the time for display
localea Locale object or a locale identifier
def format_interval(start, end, skeleton=None, tzinfo=None, fuzzy=True, locale=LC_TIME):

Format an interval between two instants according to the locale's rules.

>>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
u'15.–17.1.2016'
>>> format_interval(time(12, 12), time(16, 16), "Hm", locale="en_GB")
'12:12–16:16'
>>> format_interval(time(5, 12), time(16, 16), "hm", locale="en_US")
'5:12 AM – 4:16 PM'
>>> format_interval(time(16, 18), time(16, 24), "Hm", locale="it")
'16:18–16:24'

If the start instant equals the end instant, the interval is formatted like the instant.

>>> format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
'16:18'

Unknown skeletons fall back to "default" formatting.

>>> format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
'2015/01/01~2017/01/01'
>>> format_interval(time(16, 18), time(16, 24), "xxx", locale="ja")
'16:18:00~16:24:00'
>>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
'15.01.2016 – 17.01.2016'
Parameters
startFirst instant (datetime/date/time)
endSecond instant (datetime/date/time)
skeletonThe "skeleton format" to use for formatting.
tzinfotzinfo to use (if none is already attached)
fuzzyIf the skeleton is not found, allow choosing a skeleton that's close enough to it.
localeA locale object or identifier.
Returns
Formatted interval
def format_skeleton(skeleton, datetime=None, tzinfo=None, fuzzy=True, locale=LC_TIME):

Return a time and/or date formatted according to the given pattern.

The skeletons are defined in the CLDR data and provide more flexibility than the simple short/long/medium formats, but are a bit harder to use. The are defined using the date/time symbols without order or punctuation and map to a suitable format for the given locale.

>>> t = datetime(2007, 4, 1, 15, 30)
>>> format_skeleton('MMMEd', t, locale='fr')
u'dim. 1 avr.'
>>> format_skeleton('MMMEd', t, locale='en')
u'Sun, Apr 1'
>>> format_skeleton('yMMd', t, locale='fi')  # yMMd is not in the Finnish locale; yMd gets used
u'1.4.2007'
>>> format_skeleton('yMMd', t, fuzzy=False, locale='fi')  # yMMd is not in the Finnish locale, an error is thrown
Traceback (most recent call last):
    ...
KeyError: yMMd

After the skeleton is resolved to a pattern format_datetime is called so all timezone processing etc is the same as for that.

Parameters
skeletonA date time skeleton as defined in the cldr data.
datetimethe time or datetime object; if None, the current time in UTC is used
tzinfothe time-zone to apply to the time for display
fuzzyIf the skeleton is not found, allow choosing a skeleton that's close enough to it.
localea Locale object or a locale identifier
def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):

Return a time formatted according to the given pattern.

>>> t = time(15, 30)
>>> format_time(t, locale='en_US')
u'3:30:00 PM'
>>> format_time(t, format='short', locale='de_DE')
u'15:30'

If you don't want to use the locale default formats, you can specify a custom time pattern:

>>> format_time(t, "hh 'o''clock' a", locale='en')
u"03 o'clock PM"

For any pattern requiring the display of the time-zone a timezone has to be specified explicitly:

>>> t = datetime(2007, 4, 1, 15, 30)
>>> tzinfo = get_timezone('Europe/Paris')
>>> t = tzinfo.localize(t)
>>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
u'15:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
>>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'),
...             locale='en')
u"09 o'clock AM, Eastern Daylight Time"

As that example shows, when this function gets passed a datetime.datetime value, the actual time in the formatted string is adjusted to the timezone specified by the tzinfo parameter. If the datetime is "naive" (i.e. it has no associated timezone information), it is assumed to be in UTC.

These timezone calculations are not performed if the value is of type datetime.time, as without date information there's no way to determine what a given time would translate to in a different timezone without information about whether daylight savings time is in effect or not. This means that time values are left as-is, and the value of the tzinfo parameter is only used to display the timezone name if needed:

>>> t = time(15, 30)
>>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
...             locale='fr_FR')
u'15:30:00 heure normale d\u2019Europe centrale'
>>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
...             locale='en_US')
u'3:30:00 PM Eastern Standard Time'
Parameters
timethe time or datetime object; if None, the current time in UTC is used
formatone of "full", "long", "medium", or "short", or a custom date/time pattern
tzinfothe time-zone to apply to the time for display
localea Locale object or a locale identifier
def format_timedelta(delta, granularity='second', threshold=0.85, add_direction=False, format='long', locale=LC_TIME):

Return a time delta according to the rules of the given locale.

>>> format_timedelta(timedelta(weeks=12), locale='en_US')
u'3 months'
>>> format_timedelta(timedelta(seconds=1), locale='es')
u'1 segundo'

The granularity parameter can be provided to alter the lowest unit presented, which defaults to a second.

>>> format_timedelta(timedelta(hours=3), granularity='day',
...                  locale='en_US')
u'1 day'

The threshold parameter can be used to determine at which value the presentation switches to the next higher unit. A higher threshold factor means the presentation will switch later. For example:

>>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
u'1 day'
>>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
u'23 hours'

In addition directional information can be provided that informs the user if the date is in the past or in the future:

>>> format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
u'in 1 hour'
>>> format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
u'1 hour ago'

The format parameter controls how compact or wide the presentation is:

>>> format_timedelta(timedelta(hours=3), format='short', locale='en')
u'3 hr'
>>> format_timedelta(timedelta(hours=3), format='narrow', locale='en')
u'3h'
Parameters
deltaa timedelta object representing the time difference to format, or the delta in seconds as an int value
granularitydetermines the smallest unit that should be displayed, the value can be one of "year", "month", "week", "day", "hour", "minute" or "second"
thresholdfactor that determines at which point the presentation switches to the next higher unit
add​_directionif this flag is set to True the return value will include directional information. For instance a positive timedelta will include the information about it being in the future, a negative will be information about the value being in the past.
formatthe format, can be "narrow", "short" or "long". ( "medium" is deprecated, currently converted to "long" to maintain compatibility)
localea Locale object or a locale identifier
def get_date_format(format='medium', locale=LC_TIME):

Return the date formatting patterns used by the locale for the specified format.

>>> get_date_format(locale='en_US')
<DateTimePattern u'MMM d, y'>
>>> get_date_format('full', locale='de_DE')
<DateTimePattern u'EEEE, d. MMMM y'>
Parameters
formatthe format to use, one of "full", "long", "medium", or "short"
localethe Locale object, or a locale string
def get_datetime_format(format='medium', locale=LC_TIME):

Return the datetime formatting patterns used by the locale for the specified format.

>>> get_datetime_format(locale='en_US')
u'{1}, {0}'
Parameters
formatthe format to use, one of "full", "long", "medium", or "short"
localethe Locale object, or a locale string
def get_day_names(width='wide', context='format', locale=LC_TIME):

Return the day names used by the locale for the specified format.

>>> get_day_names('wide', locale='en_US')[1]
u'Tuesday'
>>> get_day_names('short', locale='en_US')[1]
u'Tu'
>>> get_day_names('abbreviated', locale='es')[1]
u'mar.'
>>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
u'D'
Parameters
widththe width to use, one of "wide", "abbreviated", "short" or "narrow"
contextthe context, either "format" or "stand-alone"
localethe Locale object, or a locale string
def get_era_names(width='wide', locale=LC_TIME):

Return the era names used by the locale for the specified format.

>>> get_era_names('wide', locale='en_US')[1]
u'Anno Domini'
>>> get_era_names('abbreviated', locale='de_DE')[1]
u'n. Chr.'
Parameters
widththe width to use, either "wide", "abbreviated", or "narrow"
localethe Locale object, or a locale string
def get_month_names(width='wide', context='format', locale=LC_TIME):

Return the month names used by the locale for the specified format.

>>> get_month_names('wide', locale='en_US')[1]
u'January'
>>> get_month_names('abbreviated', locale='es')[1]
u'ene.'
>>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
u'J'
Parameters
widththe width to use, one of "wide", "abbreviated", or "narrow"
contextthe context, either "format" or "stand-alone"
localethe Locale object, or a locale string
def get_next_timezone_transition(zone=None, dt=None):

Given a timezone it will return a TimezoneTransition object that holds the information about the next timezone transition that's going to happen. For instance this can be used to detect when the next DST change is going to happen and how it looks like.

The transition is calculated relative to the given datetime object. The next transition that follows the date is used. If a transition cannot be found the return value will be None.

Transition information can only be provided for timezones returned by the get_timezone function.

Parameters
zonethe timezone for which the transition should be looked up. If not provided the local timezone is used.
dtthe date after which the next transition should be found. If not given the current time is assumed.
def get_period_names(width='wide', context='stand-alone', locale=LC_TIME):

Return the names for day periods (AM/PM) used by the locale.

>>> get_period_names(locale='en_US')['am']
u'AM'
Parameters
widththe width to use, one of "abbreviated", "narrow", or "wide"
contextthe context, either "format" or "stand-alone"
localethe Locale object, or a locale string
def get_quarter_names(width='wide', context='format', locale=LC_TIME):

Return the quarter names used by the locale for the specified format.

>>> get_quarter_names('wide', locale='en_US')[1]
u'1st quarter'
>>> get_quarter_names('abbreviated', locale='de_DE')[1]
u'Q1'
>>> get_quarter_names('narrow', locale='de_DE')[1]
u'1'
Parameters
widththe width to use, one of "wide", "abbreviated", or "narrow"
contextthe context, either "format" or "stand-alone"
localethe Locale object, or a locale string
def get_time_format(format='medium', locale=LC_TIME):

Return the time formatting patterns used by the locale for the specified format.

>>> get_time_format(locale='en_US')
<DateTimePattern u'h:mm:ss a'>
>>> get_time_format('full', locale='de_DE')
<DateTimePattern u'HH:mm:ss zzzz'>
Parameters
formatthe format to use, one of "full", "long", "medium", or "short"
localethe Locale object, or a locale string
def get_timezone(zone=None):

Looks up a timezone by name and returns it. The timezone object returned comes from pytz and corresponds to the tzinfo interface and can be used with all of the functions of Babel that operate with dates.

If a timezone is not known a LookupError is raised. If zone is None a local zone object is returned.

Parameters
zonethe name of the timezone to look up. If a timezone object itself is passed in, mit's returned unchanged.
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME, return_z=False):

Return the timezone associated with the given datetime object formatted as string indicating the offset from GMT.

>>> dt = datetime(2007, 4, 1, 15, 30)
>>> get_timezone_gmt(dt, locale='en')
u'GMT+00:00'
>>> get_timezone_gmt(dt, locale='en', return_z=True)
'Z'
>>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
u'+00'
>>> tz = get_timezone('America/Los_Angeles')
>>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
>>> get_timezone_gmt(dt, locale='en')
u'GMT-07:00'
>>> get_timezone_gmt(dt, 'short', locale='en')
u'-0700'
>>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
u'-07'

The long format depends on the locale, for example in France the acronym UTC string is used instead of GMT:

>>> get_timezone_gmt(dt, 'long', locale='fr_FR')
u'UTC-07:00'
New in version 0.9.
Parameters
datetimethe datetime object; if None, the current date and time in UTC is used
widtheither "long" or "short" or "iso8601" or "iso8601_short"
localethe Locale object, or a locale string
return​_zTrue or False; Function returns indicator "Z" when local time offset is 0
def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME, return_city=False):

Return a representation of the given timezone using "location format".

The result depends on both the local display name of the country and the city associated with the time zone:

>>> tz = get_timezone('America/St_Johns')
>>> print(get_timezone_location(tz, locale='de_DE'))
Kanada (St. John’s) Zeit
>>> print(get_timezone_location(tz, locale='en'))
Canada (St. John’s) Time
>>> print(get_timezone_location(tz, locale='en', return_city=True))
St. John’s
>>> tz = get_timezone('America/Mexico_City')
>>> get_timezone_location(tz, locale='de_DE')
u'Mexiko (Mexiko-Stadt) Zeit'

If the timezone is associated with a country that uses only a single timezone, just the localized country name is returned:

>>> tz = get_timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Mitteleurop\xe4ische Zeit'
New in version 0.9.
Parameters
dt​_or​_tzinfothe datetime or tzinfo object that determines the timezone; if None, the current date and time in UTC is assumed
localethe Locale object, or a locale string
return​_cityTrue or False, if True then return exemplar city (location) for the time zone
Returns
the localized timezone name using location format
def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False, locale=LC_TIME, zone_variant=None, return_zone=False):

Return the localized display name for the given timezone. The timezone may be specified using a datetime or tzinfo object.

>>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
>>> get_timezone_name(dt, locale='en_US')
u'Pacific Standard Time'
>>> get_timezone_name(dt, locale='en_US', return_zone=True)
'America/Los_Angeles'
>>> get_timezone_name(dt, width='short', locale='en_US')
u'PST'

If this function gets passed only a tzinfo object and no concrete datetime, the returned display name is indenpendent of daylight savings time. This can be used for example for selecting timezones, or to set the time of events that recur across DST changes:

>>> tz = get_timezone('America/Los_Angeles')
>>> get_timezone_name(tz, locale='en_US')
u'Pacific Time'
>>> get_timezone_name(tz, 'short', locale='en_US')
u'PT'

If no localized display name for the timezone is available, and the timezone is associated with a country that uses only a single timezone, the name of that country is returned, formatted according to the locale:

>>> tz = get_timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Mitteleurop\xe4ische Zeit'
>>> get_timezone_name(tz, locale='pt_BR')
u'Hor\xe1rio da Europa Central'

On the other hand, if the country uses multiple timezones, the city is also included in the representation:

>>> tz = get_timezone('America/St_Johns')
>>> get_timezone_name(tz, locale='de_DE')
u'Neufundland-Zeit'

Note that short format is currently not supported for all timezones and all locales. This is partially because not every timezone has a short code in every locale. In that case it currently falls back to the long format.

For more information see LDML Appendix J: Time Zone Display Names

New in version 0.9.
Changed in version 1.0: Added zone_variant support.
Parameters
dt​_or​_tzinfothe datetime or tzinfo object that determines the timezone; if a tzinfo object is used, the resulting display name will be generic, i.e. independent of daylight savings time; if None, the current date in UTC is assumed
widtheither "long" or "short"
uncommondeprecated and ignored
localethe Locale object, or a locale string
zone​_variantdefines the zone variation to return. By default the variation is defined from the datetime object passed in. If no datetime object is passed in, the 'generic' variation is assumed. The following values are valid: 'generic', 'daylight' and 'standard'.
return​_zoneTrue or False. If true then function returns long time zone ID
def parse_date(string, locale=LC_TIME):

Parse a date from a string.

This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string.

>>> parse_date('4/1/04', locale='en_US')
datetime.date(2004, 4, 1)
>>> parse_date('01.04.2004', locale='de_DE')
datetime.date(2004, 4, 1)
Parameters
stringthe string containing the date
localea Locale object or a locale identifier
def parse_pattern(pattern):

Parse date, time, and datetime format patterns.

>>> parse_pattern("MMMMd").format
u'%(MMMM)s%(d)s'
>>> parse_pattern("MMM d, yyyy").format
u'%(MMM)s %(d)s, %(yyyy)s'

Pattern can contain literal strings in single quotes:

>>> parse_pattern("H:mm' Uhr 'z").format
u'%(H)s:%(mm)s Uhr %(z)s'

An actual single quote can be used by using two adjacent single quote characters:

>>> parse_pattern("hh' o''clock'").format
u"%(hh)s o'clock"
Parameters
patternthe formatting pattern to parse
def parse_time(string, locale=LC_TIME):

Parse a time from a string.

This function uses the time format for the locale as a hint to determine the order in which the time fields appear in the string.

>>> parse_time('15:30:00', locale='en_US')
datetime.time(15, 30)
Parameters
stringthe string containing the time
localea Locale object or a locale identifier
Returns
timethe parsed time
LC_TIME =

Undocumented

Value
default_locale('LC_TIME')
NO_INHERITANCE_MARKER: str =

Undocumented

Value
'∅∅∅'
PATTERN_CHAR_ORDER: str =

Undocumented

Value
'GyYuUQqMLlwWdDFgEecabBChHKkjJmsSAzZOvVXx'
PATTERN_CHARS: dict =

Undocumented

Value
{'G': [1, 2, 3, 4, 5],
 'y': None,
 'Y': None,
 'u': None,
 'Q': [1, 2, 3, 4, 5],
 'q': [1, 2, 3, 4, 5],
 'M': [1, 2, 3, 4, 5],
...
TIMEDELTA_UNITS =

Undocumented

Value
(('year', (3600*24)*365),
 ('month', (3600*24)*30),
 ('week', (3600*24)*7),
 ('day', 3600*24),
 ('hour', 3600),
 ('minute', 60),
 ('second', 1))
def _ensure_datetime_tzinfo(datetime, tzinfo=None):

Ensure the datetime passed has an attached tzinfo.

If the datetime is tz-naive to begin with, UTC is attached.

If a tzinfo is passed in, the datetime is normalized to that timezone.

>>> _ensure_datetime_tzinfo(datetime(2015, 1, 1)).tzinfo.zone
'UTC'
>>> tz = get_timezone("Europe/Stockholm")
>>> _ensure_datetime_tzinfo(datetime(2015, 1, 1, 13, 15, tzinfo=UTC), tzinfo=tz).hour
14
Parameters
datetimeDatetime to augment.
tzinfoOptional tznfo.
Returns
datetimedatetime with tzinfo
def _format_fallback_interval(start, end, skeleton, tzinfo, locale):

Undocumented

def _get_datetime(instant):

Get a datetime out of an "instant" (date, time, datetime, number).

Warning

The return values of this function may depend on the system clock.

If the instant is None, the current moment is used. If the instant is a time, it's augmented with today's date.

Dates are converted to naive datetimes with midnight as the time component.

>>> _get_datetime(date(2015, 1, 1))
datetime.datetime(2015, 1, 1, 0, 0)

UNIX timestamps are converted to datetimes.

>>> _get_datetime(1400000000)
datetime.datetime(2014, 5, 13, 16, 53, 20)

Other values are passed through as-is.

>>> x = datetime(2015, 1, 1)
>>> _get_datetime(x) is x
True
Parameters
instant:date|time|datetime|int|float|Nonedate, time, datetime, integer, float or None
Returns
datetimea datetime
def _get_dt_and_tzinfo(dt_or_tzinfo):

Parse a dt_or_tzinfo value into a datetime and a tzinfo.

See the docs for this function's callers for semantics.

Returns
tuple[datetime, tzinfo]Undocumented
def _get_time(time, tzinfo=None):

Get a timezoned time from a given instant.

Warning

The return values of this function may depend on the system clock.

Parameters
timetime, datetime or None
tzinfoUndocumented
Returns
timeUndocumented
def _get_tz_name(dt_or_tzinfo):
Get the timezone name out of a time, datetime, or tzinfo object.
Returns
strUndocumented
def get_period_id(time, tzinfo=None, type=None, locale=LC_TIME):

Get the day period ID for a given time.

This ID can be used as a key for the period name dictionary.

>>> get_period_names(locale="de")[get_period_id(time(7, 42), locale="de")]
u'Morgen'
Parameters
timeThe time to inspect.
tzinfoThe timezone for the time. See format_time.
typeThe period type to use. Either "selection" or None. The selection type is used for selecting among phrases such as “Your email arrived yesterday evening” or “Your email arrived last night”.
localethe Locale object, or a locale string
Returns
period ID. Something is always returned -- even if it's just "am" or "pm".
def match_skeleton(skeleton, options, allow_different_fields=False):

Find the closest match for the given datetime skeleton among the options given.

This uses the rules outlined in the TR35 document.

>>> match_skeleton('yMMd', ('yMd', 'yMMMd'))
'yMd'
>>> match_skeleton('yMMd', ('jyMMd',), allow_different_fields=True)
'jyMMd'
>>> match_skeleton('yMMd', ('qyMMd',), allow_different_fields=False)
>>> match_skeleton('hmz', ('hmv',))
'hmv'
Parameters
skeleton:strThe skeleton to match
options:Iterable[str]An iterable of other skeletons to match against
allow​_different​_fieldsUndocumented
Returns
str|NoneThe closest skeleton match, or if no match was found, None.
def split_interval_pattern(pattern):

Split an interval-describing datetime pattern into multiple pieces.

> The pattern is then designed to be broken up into two pieces by determining the first repeating field. - https://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats

>>> split_interval_pattern(u'E d.M. – E d.M.')
[u'E d.M. – ', 'E d.M.']
>>> split_interval_pattern("Y 'text' Y 'more text'")
["Y 'text '", "Y 'more text'"]
>>> split_interval_pattern(u"E, MMM d – E")
[u'E, MMM d – ', u'E']
>>> split_interval_pattern("MMM d")
['MMM d']
>>> split_interval_pattern("y G")
['y G']
>>> split_interval_pattern(u"MMM d – d")
[u'MMM d – ', u'd']
Parameters
patternInterval pattern string
Returns
list of "subpatterns"
def tokenize_pattern(pattern):

Tokenize date format patterns.

Returns a list of (token_type, token_value) tuples.

token_type may be either "chars" or "field".

For "chars" tokens, the value is the literal value.

For "field" tokens, the value is a tuple of (field character, repetition count).

Parameters
pattern:strPattern string
Returns
list[tuple]Undocumented
def untokenize_pattern(tokens):

Turn a date format pattern token stream back into a string.

This is the reverse operation of tokenize_pattern.

Parameters
tokens:Iterable[tuple]Undocumented
Returns
strUndocumented
_pattern_cache: dict =

Undocumented