Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../proc/self/root/lib64/python3....
File: _strptime.py
"""Strptime-related classes and functions.
[0] Fix | Delete
[1] Fix | Delete
CLASSES:
[2] Fix | Delete
LocaleTime -- Discovers and stores locale-specific time information
[3] Fix | Delete
TimeRE -- Creates regexes for pattern matching a string of text containing
[4] Fix | Delete
time information
[5] Fix | Delete
[6] Fix | Delete
FUNCTIONS:
[7] Fix | Delete
_getlang -- Figure out what language is being used for the locale
[8] Fix | Delete
strptime -- Calculates the time struct represented by the passed-in string
[9] Fix | Delete
[10] Fix | Delete
"""
[11] Fix | Delete
import time
[12] Fix | Delete
import locale
[13] Fix | Delete
import calendar
[14] Fix | Delete
from re import compile as re_compile
[15] Fix | Delete
from re import IGNORECASE
[16] Fix | Delete
from re import escape as re_escape
[17] Fix | Delete
from datetime import (date as datetime_date,
[18] Fix | Delete
timedelta as datetime_timedelta,
[19] Fix | Delete
timezone as datetime_timezone)
[20] Fix | Delete
from _thread import allocate_lock as _thread_allocate_lock
[21] Fix | Delete
[22] Fix | Delete
__all__ = []
[23] Fix | Delete
[24] Fix | Delete
def _getlang():
[25] Fix | Delete
# Figure out what the current language is set to.
[26] Fix | Delete
return locale.getlocale(locale.LC_TIME)
[27] Fix | Delete
[28] Fix | Delete
class LocaleTime(object):
[29] Fix | Delete
"""Stores and handles locale-specific information related to time.
[30] Fix | Delete
[31] Fix | Delete
ATTRIBUTES:
[32] Fix | Delete
f_weekday -- full weekday names (7-item list)
[33] Fix | Delete
a_weekday -- abbreviated weekday names (7-item list)
[34] Fix | Delete
f_month -- full month names (13-item list; dummy value in [0], which
[35] Fix | Delete
is added by code)
[36] Fix | Delete
a_month -- abbreviated month names (13-item list, dummy value in
[37] Fix | Delete
[0], which is added by code)
[38] Fix | Delete
am_pm -- AM/PM representation (2-item list)
[39] Fix | Delete
LC_date_time -- format string for date/time representation (string)
[40] Fix | Delete
LC_date -- format string for date representation (string)
[41] Fix | Delete
LC_time -- format string for time representation (string)
[42] Fix | Delete
timezone -- daylight- and non-daylight-savings timezone representation
[43] Fix | Delete
(2-item list of sets)
[44] Fix | Delete
lang -- Language used by instance (2-item tuple)
[45] Fix | Delete
"""
[46] Fix | Delete
[47] Fix | Delete
def __init__(self):
[48] Fix | Delete
"""Set all attributes.
[49] Fix | Delete
[50] Fix | Delete
Order of methods called matters for dependency reasons.
[51] Fix | Delete
[52] Fix | Delete
The locale language is set at the offset and then checked again before
[53] Fix | Delete
exiting. This is to make sure that the attributes were not set with a
[54] Fix | Delete
mix of information from more than one locale. This would most likely
[55] Fix | Delete
happen when using threads where one thread calls a locale-dependent
[56] Fix | Delete
function while another thread changes the locale while the function in
[57] Fix | Delete
the other thread is still running. Proper coding would call for
[58] Fix | Delete
locks to prevent changing the locale while locale-dependent code is
[59] Fix | Delete
running. The check here is done in case someone does not think about
[60] Fix | Delete
doing this.
[61] Fix | Delete
[62] Fix | Delete
Only other possible issue is if someone changed the timezone and did
[63] Fix | Delete
not call tz.tzset . That is an issue for the programmer, though,
[64] Fix | Delete
since changing the timezone is worthless without that call.
[65] Fix | Delete
[66] Fix | Delete
"""
[67] Fix | Delete
self.lang = _getlang()
[68] Fix | Delete
self.__calc_weekday()
[69] Fix | Delete
self.__calc_month()
[70] Fix | Delete
self.__calc_am_pm()
[71] Fix | Delete
self.__calc_timezone()
[72] Fix | Delete
self.__calc_date_time()
[73] Fix | Delete
if _getlang() != self.lang:
[74] Fix | Delete
raise ValueError("locale changed during initialization")
[75] Fix | Delete
if time.tzname != self.tzname or time.daylight != self.daylight:
[76] Fix | Delete
raise ValueError("timezone changed during initialization")
[77] Fix | Delete
[78] Fix | Delete
def __calc_weekday(self):
[79] Fix | Delete
# Set self.a_weekday and self.f_weekday using the calendar
[80] Fix | Delete
# module.
[81] Fix | Delete
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
[82] Fix | Delete
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
[83] Fix | Delete
self.a_weekday = a_weekday
[84] Fix | Delete
self.f_weekday = f_weekday
[85] Fix | Delete
[86] Fix | Delete
def __calc_month(self):
[87] Fix | Delete
# Set self.f_month and self.a_month using the calendar module.
[88] Fix | Delete
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
[89] Fix | Delete
f_month = [calendar.month_name[i].lower() for i in range(13)]
[90] Fix | Delete
self.a_month = a_month
[91] Fix | Delete
self.f_month = f_month
[92] Fix | Delete
[93] Fix | Delete
def __calc_am_pm(self):
[94] Fix | Delete
# Set self.am_pm by using time.strftime().
[95] Fix | Delete
[96] Fix | Delete
# The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
[97] Fix | Delete
# magical; just happened to have used it everywhere else where a
[98] Fix | Delete
# static date was needed.
[99] Fix | Delete
am_pm = []
[100] Fix | Delete
for hour in (1, 22):
[101] Fix | Delete
time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
[102] Fix | Delete
am_pm.append(time.strftime("%p", time_tuple).lower())
[103] Fix | Delete
self.am_pm = am_pm
[104] Fix | Delete
[105] Fix | Delete
def __calc_date_time(self):
[106] Fix | Delete
# Set self.date_time, self.date, & self.time by using
[107] Fix | Delete
# time.strftime().
[108] Fix | Delete
[109] Fix | Delete
# Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
[110] Fix | Delete
# overloaded numbers is minimized. The order in which searches for
[111] Fix | Delete
# values within the format string is very important; it eliminates
[112] Fix | Delete
# possible ambiguity for what something represents.
[113] Fix | Delete
time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
[114] Fix | Delete
date_time = [None, None, None]
[115] Fix | Delete
date_time[0] = time.strftime("%c", time_tuple).lower()
[116] Fix | Delete
date_time[1] = time.strftime("%x", time_tuple).lower()
[117] Fix | Delete
date_time[2] = time.strftime("%X", time_tuple).lower()
[118] Fix | Delete
replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
[119] Fix | Delete
(self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
[120] Fix | Delete
(self.a_month[3], '%b'), (self.am_pm[1], '%p'),
[121] Fix | Delete
('1999', '%Y'), ('99', '%y'), ('22', '%H'),
[122] Fix | Delete
('44', '%M'), ('55', '%S'), ('76', '%j'),
[123] Fix | Delete
('17', '%d'), ('03', '%m'), ('3', '%m'),
[124] Fix | Delete
# '3' needed for when no leading zero.
[125] Fix | Delete
('2', '%w'), ('10', '%I')]
[126] Fix | Delete
replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
[127] Fix | Delete
for tz in tz_values])
[128] Fix | Delete
for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
[129] Fix | Delete
current_format = date_time[offset]
[130] Fix | Delete
for old, new in replacement_pairs:
[131] Fix | Delete
# Must deal with possible lack of locale info
[132] Fix | Delete
# manifesting itself as the empty string (e.g., Swedish's
[133] Fix | Delete
# lack of AM/PM info) or a platform returning a tuple of empty
[134] Fix | Delete
# strings (e.g., MacOS 9 having timezone as ('','')).
[135] Fix | Delete
if old:
[136] Fix | Delete
current_format = current_format.replace(old, new)
[137] Fix | Delete
# If %W is used, then Sunday, 2005-01-03 will fall on week 0 since
[138] Fix | Delete
# 2005-01-03 occurs before the first Monday of the year. Otherwise
[139] Fix | Delete
# %U is used.
[140] Fix | Delete
time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
[141] Fix | Delete
if '00' in time.strftime(directive, time_tuple):
[142] Fix | Delete
U_W = '%W'
[143] Fix | Delete
else:
[144] Fix | Delete
U_W = '%U'
[145] Fix | Delete
date_time[offset] = current_format.replace('11', U_W)
[146] Fix | Delete
self.LC_date_time = date_time[0]
[147] Fix | Delete
self.LC_date = date_time[1]
[148] Fix | Delete
self.LC_time = date_time[2]
[149] Fix | Delete
[150] Fix | Delete
def __calc_timezone(self):
[151] Fix | Delete
# Set self.timezone by using time.tzname.
[152] Fix | Delete
# Do not worry about possibility of time.tzname[0] == time.tzname[1]
[153] Fix | Delete
# and time.daylight; handle that in strptime.
[154] Fix | Delete
try:
[155] Fix | Delete
time.tzset()
[156] Fix | Delete
except AttributeError:
[157] Fix | Delete
pass
[158] Fix | Delete
self.tzname = time.tzname
[159] Fix | Delete
self.daylight = time.daylight
[160] Fix | Delete
no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
[161] Fix | Delete
if self.daylight:
[162] Fix | Delete
has_saving = frozenset({self.tzname[1].lower()})
[163] Fix | Delete
else:
[164] Fix | Delete
has_saving = frozenset()
[165] Fix | Delete
self.timezone = (no_saving, has_saving)
[166] Fix | Delete
[167] Fix | Delete
[168] Fix | Delete
class TimeRE(dict):
[169] Fix | Delete
"""Handle conversion from format directives to regexes."""
[170] Fix | Delete
[171] Fix | Delete
def __init__(self, locale_time=None):
[172] Fix | Delete
"""Create keys/values.
[173] Fix | Delete
[174] Fix | Delete
Order of execution is important for dependency reasons.
[175] Fix | Delete
[176] Fix | Delete
"""
[177] Fix | Delete
if locale_time:
[178] Fix | Delete
self.locale_time = locale_time
[179] Fix | Delete
else:
[180] Fix | Delete
self.locale_time = LocaleTime()
[181] Fix | Delete
base = super()
[182] Fix | Delete
base.__init__({
[183] Fix | Delete
# The " \d" part of the regex is to make %c from ANSI C work
[184] Fix | Delete
'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
[185] Fix | Delete
'f': r"(?P<f>[0-9]{1,6})",
[186] Fix | Delete
'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
[187] Fix | Delete
'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
[188] Fix | Delete
'G': r"(?P<G>\d\d\d\d)",
[189] Fix | Delete
'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])",
[190] Fix | Delete
'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
[191] Fix | Delete
'M': r"(?P<M>[0-5]\d|\d)",
[192] Fix | Delete
'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
[193] Fix | Delete
'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
[194] Fix | Delete
'w': r"(?P<w>[0-6])",
[195] Fix | Delete
'u': r"(?P<u>[1-7])",
[196] Fix | Delete
'V': r"(?P<V>5[0-3]|0[1-9]|[1-4]\d|\d)",
[197] Fix | Delete
# W is set below by using 'U'
[198] Fix | Delete
'y': r"(?P<y>\d\d)",
[199] Fix | Delete
#XXX: Does 'Y' need to worry about having less or more than
[200] Fix | Delete
# 4 digits?
[201] Fix | Delete
'Y': r"(?P<Y>\d\d\d\d)",
[202] Fix | Delete
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|Z)",
[203] Fix | Delete
'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
[204] Fix | Delete
'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
[205] Fix | Delete
'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
[206] Fix | Delete
'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'),
[207] Fix | Delete
'p': self.__seqToRE(self.locale_time.am_pm, 'p'),
[208] Fix | Delete
'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone
[209] Fix | Delete
for tz in tz_names),
[210] Fix | Delete
'Z'),
[211] Fix | Delete
'%': '%'})
[212] Fix | Delete
base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
[213] Fix | Delete
base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
[214] Fix | Delete
base.__setitem__('x', self.pattern(self.locale_time.LC_date))
[215] Fix | Delete
base.__setitem__('X', self.pattern(self.locale_time.LC_time))
[216] Fix | Delete
[217] Fix | Delete
def __seqToRE(self, to_convert, directive):
[218] Fix | Delete
"""Convert a list to a regex string for matching a directive.
[219] Fix | Delete
[220] Fix | Delete
Want possible matching values to be from longest to shortest. This
[221] Fix | Delete
prevents the possibility of a match occurring for a value that also
[222] Fix | Delete
a substring of a larger value that should have matched (e.g., 'abc'
[223] Fix | Delete
matching when 'abcdef' should have been the match).
[224] Fix | Delete
[225] Fix | Delete
"""
[226] Fix | Delete
to_convert = sorted(to_convert, key=len, reverse=True)
[227] Fix | Delete
for value in to_convert:
[228] Fix | Delete
if value != '':
[229] Fix | Delete
break
[230] Fix | Delete
else:
[231] Fix | Delete
return ''
[232] Fix | Delete
regex = '|'.join(re_escape(stuff) for stuff in to_convert)
[233] Fix | Delete
regex = '(?P<%s>%s' % (directive, regex)
[234] Fix | Delete
return '%s)' % regex
[235] Fix | Delete
[236] Fix | Delete
def pattern(self, format):
[237] Fix | Delete
"""Return regex pattern for the format string.
[238] Fix | Delete
[239] Fix | Delete
Need to make sure that any characters that might be interpreted as
[240] Fix | Delete
regex syntax are escaped.
[241] Fix | Delete
[242] Fix | Delete
"""
[243] Fix | Delete
processed_format = ''
[244] Fix | Delete
# The sub() call escapes all characters that might be misconstrued
[245] Fix | Delete
# as regex syntax. Cannot use re.escape since we have to deal with
[246] Fix | Delete
# format directives (%m, etc.).
[247] Fix | Delete
regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
[248] Fix | Delete
format = regex_chars.sub(r"\\\1", format)
[249] Fix | Delete
whitespace_replacement = re_compile(r'\s+')
[250] Fix | Delete
format = whitespace_replacement.sub(r'\\s+', format)
[251] Fix | Delete
while '%' in format:
[252] Fix | Delete
directive_index = format.index('%')+1
[253] Fix | Delete
processed_format = "%s%s%s" % (processed_format,
[254] Fix | Delete
format[:directive_index-1],
[255] Fix | Delete
self[format[directive_index]])
[256] Fix | Delete
format = format[directive_index+1:]
[257] Fix | Delete
return "%s%s" % (processed_format, format)
[258] Fix | Delete
[259] Fix | Delete
def compile(self, format):
[260] Fix | Delete
"""Return a compiled re object for the format string."""
[261] Fix | Delete
return re_compile(self.pattern(format), IGNORECASE)
[262] Fix | Delete
[263] Fix | Delete
_cache_lock = _thread_allocate_lock()
[264] Fix | Delete
# DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock
[265] Fix | Delete
# first!
[266] Fix | Delete
_TimeRE_cache = TimeRE()
[267] Fix | Delete
_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache
[268] Fix | Delete
_regex_cache = {}
[269] Fix | Delete
[270] Fix | Delete
def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
[271] Fix | Delete
"""Calculate the Julian day based on the year, week of the year, and day of
[272] Fix | Delete
the week, with week_start_day representing whether the week of the year
[273] Fix | Delete
assumes the week starts on Sunday or Monday (6 or 0)."""
[274] Fix | Delete
first_weekday = datetime_date(year, 1, 1).weekday()
[275] Fix | Delete
# If we are dealing with the %U directive (week starts on Sunday), it's
[276] Fix | Delete
# easier to just shift the view to Sunday being the first day of the
[277] Fix | Delete
# week.
[278] Fix | Delete
if not week_starts_Mon:
[279] Fix | Delete
first_weekday = (first_weekday + 1) % 7
[280] Fix | Delete
day_of_week = (day_of_week + 1) % 7
[281] Fix | Delete
# Need to watch out for a week 0 (when the first day of the year is not
[282] Fix | Delete
# the same as that specified by %U or %W).
[283] Fix | Delete
week_0_length = (7 - first_weekday) % 7
[284] Fix | Delete
if week_of_year == 0:
[285] Fix | Delete
return 1 + day_of_week - first_weekday
[286] Fix | Delete
else:
[287] Fix | Delete
days_to_week = week_0_length + (7 * (week_of_year - 1))
[288] Fix | Delete
return 1 + days_to_week + day_of_week
[289] Fix | Delete
[290] Fix | Delete
[291] Fix | Delete
def _calc_julian_from_V(iso_year, iso_week, iso_weekday):
[292] Fix | Delete
"""Calculate the Julian day based on the ISO 8601 year, week, and weekday.
[293] Fix | Delete
ISO weeks start on Mondays, with week 01 being the week containing 4 Jan.
[294] Fix | Delete
ISO week days range from 1 (Monday) to 7 (Sunday).
[295] Fix | Delete
"""
[296] Fix | Delete
correction = datetime_date(iso_year, 1, 4).isoweekday() + 3
[297] Fix | Delete
ordinal = (iso_week * 7) + iso_weekday - correction
[298] Fix | Delete
# ordinal may be negative or 0 now, which means the date is in the previous
[299] Fix | Delete
# calendar year
[300] Fix | Delete
if ordinal < 1:
[301] Fix | Delete
ordinal += datetime_date(iso_year, 1, 1).toordinal()
[302] Fix | Delete
iso_year -= 1
[303] Fix | Delete
ordinal -= datetime_date(iso_year, 1, 1).toordinal()
[304] Fix | Delete
return iso_year, ordinal
[305] Fix | Delete
[306] Fix | Delete
[307] Fix | Delete
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
[308] Fix | Delete
"""Return a 2-tuple consisting of a time struct and an int containing
[309] Fix | Delete
the number of microseconds based on the input string and the
[310] Fix | Delete
format string."""
[311] Fix | Delete
[312] Fix | Delete
for index, arg in enumerate([data_string, format]):
[313] Fix | Delete
if not isinstance(arg, str):
[314] Fix | Delete
msg = "strptime() argument {} must be str, not {}"
[315] Fix | Delete
raise TypeError(msg.format(index, type(arg)))
[316] Fix | Delete
[317] Fix | Delete
global _TimeRE_cache, _regex_cache
[318] Fix | Delete
with _cache_lock:
[319] Fix | Delete
locale_time = _TimeRE_cache.locale_time
[320] Fix | Delete
if (_getlang() != locale_time.lang or
[321] Fix | Delete
time.tzname != locale_time.tzname or
[322] Fix | Delete
time.daylight != locale_time.daylight):
[323] Fix | Delete
_TimeRE_cache = TimeRE()
[324] Fix | Delete
_regex_cache.clear()
[325] Fix | Delete
locale_time = _TimeRE_cache.locale_time
[326] Fix | Delete
if len(_regex_cache) > _CACHE_MAX_SIZE:
[327] Fix | Delete
_regex_cache.clear()
[328] Fix | Delete
format_regex = _regex_cache.get(format)
[329] Fix | Delete
if not format_regex:
[330] Fix | Delete
try:
[331] Fix | Delete
format_regex = _TimeRE_cache.compile(format)
[332] Fix | Delete
# KeyError raised when a bad format is found; can be specified as
[333] Fix | Delete
# \\, in which case it was a stray % but with a space after it
[334] Fix | Delete
except KeyError as err:
[335] Fix | Delete
bad_directive = err.args[0]
[336] Fix | Delete
if bad_directive == "\\":
[337] Fix | Delete
bad_directive = "%"
[338] Fix | Delete
del err
[339] Fix | Delete
raise ValueError("'%s' is a bad directive in format '%s'" %
[340] Fix | Delete
(bad_directive, format)) from None
[341] Fix | Delete
# IndexError only occurs when the format string is "%"
[342] Fix | Delete
except IndexError:
[343] Fix | Delete
raise ValueError("stray %% in format '%s'" % format) from None
[344] Fix | Delete
_regex_cache[format] = format_regex
[345] Fix | Delete
found = format_regex.match(data_string)
[346] Fix | Delete
if not found:
[347] Fix | Delete
raise ValueError("time data %r does not match format %r" %
[348] Fix | Delete
(data_string, format))
[349] Fix | Delete
if len(data_string) != found.end():
[350] Fix | Delete
raise ValueError("unconverted data remains: %s" %
[351] Fix | Delete
data_string[found.end():])
[352] Fix | Delete
[353] Fix | Delete
iso_year = year = None
[354] Fix | Delete
month = day = 1
[355] Fix | Delete
hour = minute = second = fraction = 0
[356] Fix | Delete
tz = -1
[357] Fix | Delete
gmtoff = None
[358] Fix | Delete
gmtoff_fraction = 0
[359] Fix | Delete
# Default to -1 to signify that values not known; not critical to have,
[360] Fix | Delete
# though
[361] Fix | Delete
iso_week = week_of_year = None
[362] Fix | Delete
week_of_year_start = None
[363] Fix | Delete
# weekday and julian defaulted to None so as to signal need to calculate
[364] Fix | Delete
# values
[365] Fix | Delete
weekday = julian = None
[366] Fix | Delete
found_dict = found.groupdict()
[367] Fix | Delete
for group_key in found_dict.keys():
[368] Fix | Delete
# Directives not explicitly handled below:
[369] Fix | Delete
# c, x, X
[370] Fix | Delete
# handled by making out of other directives
[371] Fix | Delete
# U, W
[372] Fix | Delete
# worthless without day of the week
[373] Fix | Delete
if group_key == 'y':
[374] Fix | Delete
year = int(found_dict['y'])
[375] Fix | Delete
# Open Group specification for strptime() states that a %y
[376] Fix | Delete
#value in the range of [00, 68] is in the century 2000, while
[377] Fix | Delete
#[69,99] is in the century 1900
[378] Fix | Delete
if year <= 68:
[379] Fix | Delete
year += 2000
[380] Fix | Delete
else:
[381] Fix | Delete
year += 1900
[382] Fix | Delete
elif group_key == 'Y':
[383] Fix | Delete
year = int(found_dict['Y'])
[384] Fix | Delete
elif group_key == 'G':
[385] Fix | Delete
iso_year = int(found_dict['G'])
[386] Fix | Delete
elif group_key == 'm':
[387] Fix | Delete
month = int(found_dict['m'])
[388] Fix | Delete
elif group_key == 'B':
[389] Fix | Delete
month = locale_time.f_month.index(found_dict['B'].lower())
[390] Fix | Delete
elif group_key == 'b':
[391] Fix | Delete
month = locale_time.a_month.index(found_dict['b'].lower())
[392] Fix | Delete
elif group_key == 'd':
[393] Fix | Delete
day = int(found_dict['d'])
[394] Fix | Delete
elif group_key == 'H':
[395] Fix | Delete
hour = int(found_dict['H'])
[396] Fix | Delete
elif group_key == 'I':
[397] Fix | Delete
hour = int(found_dict['I'])
[398] Fix | Delete
ampm = found_dict.get('p', '').lower()
[399] Fix | Delete
# If there was no AM/PM indicator, we'll treat this like AM
[400] Fix | Delete
if ampm in ('', locale_time.am_pm[0]):
[401] Fix | Delete
# We're in AM so the hour is correct unless we're
[402] Fix | Delete
# looking at 12 midnight.
[403] Fix | Delete
# 12 midnight == 12 AM == hour 0
[404] Fix | Delete
if hour == 12:
[405] Fix | Delete
hour = 0
[406] Fix | Delete
elif ampm == locale_time.am_pm[1]:
[407] Fix | Delete
# We're in PM so we need to add 12 to the hour unless
[408] Fix | Delete
# we're looking at 12 noon.
[409] Fix | Delete
# 12 noon == 12 PM == hour 12
[410] Fix | Delete
if hour != 12:
[411] Fix | Delete
hour += 12
[412] Fix | Delete
elif group_key == 'M':
[413] Fix | Delete
minute = int(found_dict['M'])
[414] Fix | Delete
elif group_key == 'S':
[415] Fix | Delete
second = int(found_dict['S'])
[416] Fix | Delete
elif group_key == 'f':
[417] Fix | Delete
s = found_dict['f']
[418] Fix | Delete
# Pad to always return microseconds.
[419] Fix | Delete
s += "0" * (6 - len(s))
[420] Fix | Delete
fraction = int(s)
[421] Fix | Delete
elif group_key == 'A':
[422] Fix | Delete
weekday = locale_time.f_weekday.index(found_dict['A'].lower())
[423] Fix | Delete
elif group_key == 'a':
[424] Fix | Delete
weekday = locale_time.a_weekday.index(found_dict['a'].lower())
[425] Fix | Delete
elif group_key == 'w':
[426] Fix | Delete
weekday = int(found_dict['w'])
[427] Fix | Delete
if weekday == 0:
[428] Fix | Delete
weekday = 6
[429] Fix | Delete
else:
[430] Fix | Delete
weekday -= 1
[431] Fix | Delete
elif group_key == 'u':
[432] Fix | Delete
weekday = int(found_dict['u'])
[433] Fix | Delete
weekday -= 1
[434] Fix | Delete
elif group_key == 'j':
[435] Fix | Delete
julian = int(found_dict['j'])
[436] Fix | Delete
elif group_key in ('U', 'W'):
[437] Fix | Delete
week_of_year = int(found_dict[group_key])
[438] Fix | Delete
if group_key == 'U':
[439] Fix | Delete
# U starts week on Sunday.
[440] Fix | Delete
week_of_year_start = 6
[441] Fix | Delete
else:
[442] Fix | Delete
# W starts week on Monday.
[443] Fix | Delete
week_of_year_start = 0
[444] Fix | Delete
elif group_key == 'V':
[445] Fix | Delete
iso_week = int(found_dict['V'])
[446] Fix | Delete
elif group_key == 'z':
[447] Fix | Delete
z = found_dict['z']
[448] Fix | Delete
if z == 'Z':
[449] Fix | Delete
gmtoff = 0
[450] Fix | Delete
else:
[451] Fix | Delete
if z[3] == ':':
[452] Fix | Delete
z = z[:3] + z[4:]
[453] Fix | Delete
if len(z) > 5:
[454] Fix | Delete
if z[5] != ':':
[455] Fix | Delete
msg = f"Inconsistent use of : in {found_dict['z']}"
[456] Fix | Delete
raise ValueError(msg)
[457] Fix | Delete
z = z[:5] + z[6:]
[458] Fix | Delete
hours = int(z[1:3])
[459] Fix | Delete
minutes = int(z[3:5])
[460] Fix | Delete
seconds = int(z[5:7] or 0)
[461] Fix | Delete
gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds
[462] Fix | Delete
gmtoff_remainder = z[8:]
[463] Fix | Delete
# Pad to always return microseconds.
[464] Fix | Delete
gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))
[465] Fix | Delete
gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)
[466] Fix | Delete
if z.startswith("-"):
[467] Fix | Delete
gmtoff = -gmtoff
[468] Fix | Delete
gmtoff_fraction = -gmtoff_fraction
[469] Fix | Delete
elif group_key == 'Z':
[470] Fix | Delete
# Since -1 is default value only need to worry about setting tz if
[471] Fix | Delete
# it can be something other than -1.
[472] Fix | Delete
found_zone = found_dict['Z'].lower()
[473] Fix | Delete
for value, tz_values in enumerate(locale_time.timezone):
[474] Fix | Delete
if found_zone in tz_values:
[475] Fix | Delete
# Deal with bad locale setup where timezone names are the
[476] Fix | Delete
# same and yet time.daylight is true; too ambiguous to
[477] Fix | Delete
# be able to tell what timezone has daylight savings
[478] Fix | Delete
if (time.tzname[0] == time.tzname[1] and
[479] Fix | Delete
time.daylight and found_zone not in ("utc", "gmt")):
[480] Fix | Delete
break
[481] Fix | Delete
else:
[482] Fix | Delete
tz = value
[483] Fix | Delete
break
[484] Fix | Delete
# Deal with the cases where ambiguities arize
[485] Fix | Delete
# don't assume default values for ISO week/year
[486] Fix | Delete
if year is None and iso_year is not None:
[487] Fix | Delete
if iso_week is None or weekday is None:
[488] Fix | Delete
raise ValueError("ISO year directive '%G' must be used with "
[489] Fix | Delete
"the ISO week directive '%V' and a weekday "
[490] Fix | Delete
"directive ('%A', '%a', '%w', or '%u').")
[491] Fix | Delete
if julian is not None:
[492] Fix | Delete
raise ValueError("Day of the year directive '%j' is not "
[493] Fix | Delete
"compatible with ISO year directive '%G'. "
[494] Fix | Delete
"Use '%Y' instead.")
[495] Fix | Delete
elif week_of_year is None and iso_week is not None:
[496] Fix | Delete
if weekday is None:
[497] Fix | Delete
raise ValueError("ISO week directive '%V' must be used with "
[498] Fix | Delete
"the ISO year directive '%G' and a weekday "
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function