Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
isostrf.py215 linesDownload Raw Back to isodate
1##############################################################################2# Copyright 2009, Gerhard Weis3# All rights reserved.4#5# Redistribution and use in source and binary forms, with or without6# modification, are permitted provided that the following conditions are met:7#8#  * Redistributions of source code must retain the above copyright notice,9#    this list of conditions and the following disclaimer.10#  * Redistributions in binary form must reproduce the above copyright notice,11#    this list of conditions and the following disclaimer in the documentation12#    and/or other materials provided with the distribution.13#  * Neither the name of the authors nor the names of its contributors14#    may be used to endorse or promote products derived from this software15#    without specific prior written permission.16#17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"18# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE20# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE21# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR22# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF23# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS24# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN25# CONTRACT, STRICT LIABILITY, OR TORT26##############################################################################27"""28This module provides an alternative strftime method.29 30The strftime method in this module allows only a subset of Python's strftime31format codes, plus a few additional. It supports the full range of date values32possible with standard Python date/time objects. Furthermore there are several33pr-defined format strings in this module to make ease producing of ISO 860134conforming strings.35"""36import re37from datetime import date, timedelta38 39from isodate.duration import Duration40from isodate.isotzinfo import tz_isoformat41 42# Date specific format strings43DATE_BAS_COMPLETE = '%Y%m%d'44DATE_EXT_COMPLETE = '%Y-%m-%d'45DATE_BAS_WEEK_COMPLETE = '%YW%W%w'46DATE_EXT_WEEK_COMPLETE = '%Y-W%W-%w'47DATE_BAS_ORD_COMPLETE = '%Y%j'48DATE_EXT_ORD_COMPLETE = '%Y-%j'49DATE_BAS_WEEK = '%YW%W'50DATE_EXT_WEEK = '%Y-W%W'51DATE_BAS_MONTH = '%Y%m'52DATE_EXT_MONTH = '%Y-%m'53DATE_YEAR = '%Y'54DATE_CENTURY = '%C'55 56# Time specific format strings57TIME_BAS_COMPLETE = '%H%M%S'58TIME_EXT_COMPLETE = '%H:%M:%S'59TIME_BAS_MINUTE = '%H%M'60TIME_EXT_MINUTE = '%H:%M'61TIME_HOUR = '%H'62 63# Time zone formats64TZ_BAS = '%z'65TZ_EXT = '%Z'66TZ_HOUR = '%h'67 68# DateTime formats69DT_EXT_COMPLETE = DATE_EXT_COMPLETE + 'T' + TIME_EXT_COMPLETE + TZ_EXT70DT_BAS_COMPLETE = DATE_BAS_COMPLETE + 'T' + TIME_BAS_COMPLETE + TZ_BAS71DT_EXT_ORD_COMPLETE = DATE_EXT_ORD_COMPLETE + 'T' + TIME_EXT_COMPLETE + TZ_EXT72DT_BAS_ORD_COMPLETE = DATE_BAS_ORD_COMPLETE + 'T' + TIME_BAS_COMPLETE + TZ_BAS73DT_EXT_WEEK_COMPLETE = (DATE_EXT_WEEK_COMPLETE + 'T' +74                        TIME_EXT_COMPLETE + TZ_EXT)75DT_BAS_WEEK_COMPLETE = (DATE_BAS_WEEK_COMPLETE + 'T' +76                        TIME_BAS_COMPLETE + TZ_BAS)77 78# Duration formts79D_DEFAULT = 'P%P'80D_WEEK = 'P%p'81D_ALT_EXT = 'P' + DATE_EXT_COMPLETE + 'T' + TIME_EXT_COMPLETE82D_ALT_BAS = 'P' + DATE_BAS_COMPLETE + 'T' + TIME_BAS_COMPLETE83D_ALT_EXT_ORD = 'P' + DATE_EXT_ORD_COMPLETE + 'T' + TIME_EXT_COMPLETE84D_ALT_BAS_ORD = 'P' + DATE_BAS_ORD_COMPLETE + 'T' + TIME_BAS_COMPLETE85 86STRF_DT_MAP = {'%d': lambda tdt, yds: '%02d' % tdt.day,87               '%f': lambda tdt, yds: '%06d' % tdt.microsecond,88               '%H': lambda tdt, yds: '%02d' % tdt.hour,89               '%j': lambda tdt, yds: '%03d' % (tdt.toordinal() -90                                                date(tdt.year,91                                                     1, 1).toordinal() +92                                                1),93               '%m': lambda tdt, yds: '%02d' % tdt.month,94               '%M': lambda tdt, yds: '%02d' % tdt.minute,95               '%S': lambda tdt, yds: '%02d' % tdt.second,96               '%w': lambda tdt, yds: '%1d' % tdt.isoweekday(),97               '%W': lambda tdt, yds: '%02d' % tdt.isocalendar()[1],98               '%Y': lambda tdt, yds: (((yds != 4) and '+') or '') +99                                      (('%%0%dd' % yds) % tdt.year),100               '%C': lambda tdt, yds: (((yds != 4) and '+') or '') +101                                      (('%%0%dd' % (yds - 2)) %102                                       (tdt.year / 100)),103               '%h': lambda tdt, yds: tz_isoformat(tdt, '%h'),104               '%Z': lambda tdt, yds: tz_isoformat(tdt, '%Z'),105               '%z': lambda tdt, yds: tz_isoformat(tdt, '%z'),106               '%%': lambda tdt, yds: '%'}107 108STRF_D_MAP = {'%d': lambda tdt, yds: '%02d' % tdt.days,109              '%f': lambda tdt, yds: '%06d' % tdt.microseconds,110              '%H': lambda tdt, yds: '%02d' % (tdt.seconds / 60 / 60),111              '%m': lambda tdt, yds: '%02d' % tdt.months,112              '%M': lambda tdt, yds: '%02d' % ((tdt.seconds / 60) % 60),113              '%S': lambda tdt, yds: '%02d' % (tdt.seconds % 60),114              '%W': lambda tdt, yds: '%02d' % (abs(tdt.days / 7)),115              '%Y': lambda tdt, yds: (((yds != 4) and '+') or '') +116                                     (('%%0%dd' % yds) % tdt.years),117              '%C': lambda tdt, yds: (((yds != 4) and '+') or '') +118                                     (('%%0%dd' % (yds - 2)) %119                                      (tdt.years / 100)),120              '%%': lambda tdt, yds: '%'}121 122 123def _strfduration(tdt, format, yeardigits=4):124    '''125    this is the work method for timedelta and Duration instances.126 127    see strftime for more details.128    '''129    def repl(match):130        '''131        lookup format command and return corresponding replacement.132        '''133        if match.group(0) in STRF_D_MAP:134            return STRF_D_MAP[match.group(0)](tdt, yeardigits)135        elif match.group(0) == '%P':136            ret = []137            if isinstance(tdt, Duration):138                if tdt.years:139                    ret.append('%sY' % abs(tdt.years))140                if tdt.months:141                    ret.append('%sM' % abs(tdt.months))142            usecs = abs((tdt.days * 24 * 60 * 60 + tdt.seconds) * 1000000 +143                        tdt.microseconds)144            seconds, usecs = divmod(usecs, 1000000)145            minutes, seconds = divmod(seconds, 60)146            hours, minutes = divmod(minutes, 60)147            days, hours = divmod(hours, 24)148            if days:149                ret.append('%sD' % days)150            if hours or minutes or seconds or usecs:151                ret.append('T')152                if hours:153                    ret.append('%sH' % hours)154                if minutes:155                    ret.append('%sM' % minutes)156                if seconds or usecs:157                    if usecs:158                        ret.append(("%d.%06d" % (seconds, usecs)).rstrip('0'))159                    else:160                        ret.append("%d" % seconds)161                    ret.append('S')162            # at least one component has to be there.163            return ret and ''.join(ret) or '0D'164        elif match.group(0) == '%p':165            return str(abs(tdt.days // 7)) + 'W'166        return match.group(0)167    return re.sub('%d|%f|%H|%m|%M|%S|%W|%Y|%C|%%|%P|%p', repl,168                  format)169 170 171def _strfdt(tdt, format, yeardigits=4):172    '''173    this is the work method for time and date instances.174 175    see strftime for more details.176    '''177    def repl(match):178        '''179        lookup format command and return corresponding replacement.180        '''181        if match.group(0) in STRF_DT_MAP:182            return STRF_DT_MAP[match.group(0)](tdt, yeardigits)183        return match.group(0)184    return re.sub('%d|%f|%H|%j|%m|%M|%S|%w|%W|%Y|%C|%z|%Z|%h|%%', repl,185                  format)186 187 188def strftime(tdt, format, yeardigits=4):189    '''Directive    Meaning    Notes190    %d    Day of the month as a decimal number [01,31].191    %f    Microsecond as a decimal number [0,999999], zero-padded192          on the left (1)193    %H    Hour (24-hour clock) as a decimal number [00,23].194    %j    Day of the year as a decimal number [001,366].195    %m    Month as a decimal number [01,12].196    %M    Minute as a decimal number [00,59].197    %S    Second as a decimal number [00,61].    (3)198    %w    Weekday as a decimal number [0(Monday),6].199    %W    Week number of the year (Monday as the first day of the week)200          as a decimal number [00,53]. All days in a new year preceding the201          first Monday are considered to be in week 0.  (4)202    %Y    Year with century as a decimal number. [0000,9999]203    %C    Century as a decimal number. [00,99]204    %z    UTC offset in the form +HHMM or -HHMM (empty string if the205          object is naive).    (5)206    %Z    Time zone name (empty string if the object is naive).207    %P    ISO8601 duration format.208    %p    ISO8601 duration format in weeks.209    %%    A literal '%' character.210 211    '''212    if isinstance(tdt, (timedelta, Duration)):213        return _strfduration(tdt, format, yeardigits)214    return _strfdt(tdt, format, yeardigits)215 
codekingpro/portable-devtools · Team Ai