teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

修正

2019/10/22 06:40

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -33,9 +33,13 @@
33
33
  **参考**
34
34
  - [組み込み型 - str — Python 3.8.0 ドキュメント](https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str)
35
35
 
36
- ### ****
36
+ ### **無理にでもstrftimeを使う方法**
37
+ 思い付きです。避けた方が良いでしょう。
37
38
  ```Python
38
39
  print(
39
- (datetime.datetime(2000, 1, 1) + p3).strftime('%H:%M')
40
+ (datetime.datetime(2000, 1, 1) + p3).strftime('%H:%M') # ただし、形式は 03:00
40
41
  )
41
- ```
42
+ ```
43
+
44
+ どうしても 3:00 と出力したい場合、Linuxであればフォーマット %-I:%M が使えるそうです。
45
+ [Python datetime formatting without zero-padding - Stack Overflow](https://stackoverflow.com/questions/9525944/python-datetime-formatting-without-zero-padding)

2

追記

2019/10/22 06:40

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -31,4 +31,11 @@
31
31
  ```
32
32
 
33
33
  **参考**
34
- - [組み込み型 - str — Python 3.8.0 ドキュメント](https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str)
34
+ - [組み込み型 - str — Python 3.8.0 ドキュメント](https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str)
35
+
36
+ ### ****
37
+ ```Python
38
+ print(
39
+ (datetime.datetime(2000, 1, 1) + p3).strftime('%H:%M')
40
+ )
41
+ ```

1

追記

2019/10/22 06:37

投稿

LouiS0616
LouiS0616

スコア35678

answer CHANGED
@@ -3,7 +3,10 @@
3
3
 
4
4
  timedeltaオブジェクト(p3)を何らかの方法で文字列化してやる必要があります。
5
5
 
6
- **必要な情報を計算する方法**
6
+ ### **必要な情報を計算する方法**
7
+ timedeltaオブジェクトは days, seconds, microseconds しか提供していません。
8
+ 面倒ですが時分は自力で計算します。
9
+
7
10
  ```Python
8
11
  minites, seconds = divmod(p3.seconds, 60)
9
12
  hours, minites = divmod(minites, 60)
@@ -12,10 +15,20 @@
12
15
  print(f'{hours}:{minites:02d}')
13
16
  ```
14
17
 
18
+ **参考**
19
+ - [datetime - timedelta — Python 3.8.0 ドキュメント](https://docs.python.org/ja/3/library/datetime.html#timedelta-objects)
20
+ - [組み込み関数- divmod — Python 3.8.0 ドキュメント](https://docs.python.org/ja/3/library/functions.html#divmod)
15
21
 
16
- **不要な情報を削ぎ落す方法**
22
+ ### **不要な情報を削ぎ落す方法**
23
+ 邪道な気がしますが、楽ではあります。
17
24
  ```Python
18
25
  print(str(p3).rsplit(':', 1)[0])
19
26
  ```
20
27
 
28
+ あるいは
21
- 後者は邪道な感がしますが、楽ではあります。
29
+ ```Python
30
+ print(str(p3).rstrip('0123456789')[:-1])
31
+ ```
32
+
33
+ **参考**
34
+ - [組み込み型 - str — Python 3.8.0 ドキュメント](https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str)