Coverage for mypackage / mypackage.py: 99%

43 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2025-12-21 13:48 +0900

1# -*- coding: utf-8 -*- 

2 

3'''mypackage 

4 

5Copyright ycookjp 

6https://github.com/ycookjp/ 

7 

8''' 

9 

10from datetime import datetime 

11 

12def find_repeat(target: str, sub: str, start: int=0, end: int=-1): 

13 ''' 

14  

15 部分文字列が最初に出現した位置と連続する出現回数を取得します。 

16  

17 Args: 

18 target (str): 部分文字列を探す対象の文字列を指定します。 

19 sub (str): 出現を調べる部分文字列を指定します。 

20 start (int, optional): 部分文字列の出現を調べる範囲の開始 

21 位置のインデックスを指定します。省略した時は、文字列の最初から 

22 出現を調べます。 

23 end (int, optional): 部分文字列の出現を調べる範囲の終了位置 

24 (指定されたインデックスの1つ前までを調べる)を指定します。 

25  

26 Returns: 

27 list: 最初の養子に部分文字列が最初に出現した位置のインデックス、 

28 2番目の要素に出現回数を設定した配列を返します。 

29  

30 ''' 

31 if end < 0: 

32 end = len(target) 

33 

34 pos: int = target.find(sub, start, end) 

35 count: int = 0 

36 

37 if pos >= 0: 

38 next_pos: int = pos 

39 while next_pos >= 0: 

40 count += 1 

41 next_pos: int = target.find(sub, next_pos + len(sub), end) 

42 

43 return [pos, count] 

44 

45def format_date(date: datetime, formatstr: str): 

46 ''' 

47  

48 書式文字列に従って datetime を文字列に変換します。 

49 書式文字列の変換規則は以下のとおりです。 

50  

51 * 書式文字列に'y', 'M', 'd', 'h', 'm', 's' の文字が含まれる場合、その部分を 

52 それぞれ date の年、月、時、分、秒に置換します。 

53 * 上記の文字が連続する場合は数値の桁を定義したことになります。連続する文字 

54 の個数よりも数値の桁が小さい場合は、数値の前に所定の桁数になるまで"0"を 

55 追加します。 

56 * 書式文字列が"7"の場合、数値(年)の桁数が書式文字列で設定された桁数より 

57 大きい場合は、書式文字列の桁数になるように数値の左側を切り捨てます。 

58  

59 Args: 

60 date (datetime): datetimeオブジェクト 

61 formatstr (str): 書式文字列 

62 Returns: 

63 srr: 書式文字列に従って変換された文字列を返します。 

64 ''' 

65 converted: str = "" 

66 start: int = 0 

67 end: int = len(formatstr) 

68 

69 while start < end: 

70 c = formatstr[start] 

71 if c == "y" or c == "M" or c == "d" or c == "h" or c == "m" or c == "s": 

72 datechar = formatstr[start] 

73 found = find_repeat(formatstr, datechar, start, end) 

74 count = found[1] 

75 

76 if datechar == "y": 

77 val = str(date.year) 

78 

79 if len(val) > count: 

80 val = val[len(val)-count:len(val)] 

81 else: 

82 if datechar == "M": 

83 val = str(date.month) 

84 elif datechar == "d": 

85 val = str(date.day) 

86 elif datechar == "h": 

87 val = str(date.hour) 

88 elif datechar == "m": 

89 val = str(date.minute) 

90 elif datechar == "s": 90 ↛ 93line 90 didn't jump to line 93 because the condition on line 90 was always true

91 val = str(date.second) 

92 

93 if len(val) < count: 

94 val = "0" * (count - len(val)) + val 

95 converted = converted + val 

96 start = start + count 

97 else: 

98 converted = converted + formatstr[start] 

99 start += 1 

100 

101 return converted