質問編集履歴

1

コードのイメージを追加しました。よろしくお願い致します。

2020/10/07 01:25

投稿

supermaruetsu
supermaruetsu

スコア148

test CHANGED
File without changes
test CHANGED
@@ -10,16 +10,42 @@
10
10
 
11
11
 
12
12
 
13
- now = datetime.datetime.now()
13
+ def find_nearest_datetime():
14
14
 
15
- now2 = datetime.datetime.now()
16
-
17
- now3 = datetime.datetime.now()
18
-
19
- now_list = [now,now2,now3]
15
+ starget_time = '2020-09-19 01:20:29'
20
16
 
21
17
 
22
18
 
19
+ tdatetime1 = datetime.datetime.strptime('2020-09-19 01:18:29', '%Y-%m-%d %H:%M:%S')
20
+
21
+ tdatetime2 = datetime.datetime.strptime('2020-09-19 01:19:29', '%Y-%m-%d %H:%M:%S')
22
+
23
+ tdatetime3 = datetime.datetime.strptime(starget_time, '%Y-%m-%d %H:%M:%S')
24
+
25
+ tdatetime4 = datetime.datetime.strptime('2020-09-19 01:21:29', '%Y-%m-%d %H:%M:%S')
26
+
27
+ tdatetime5 = datetime.datetime.strptime('2020-09-19 01:22:29', '%Y-%m-%d %H:%M:%S')
28
+
29
+
30
+
31
+ datetime_list = [tdatetime1,tdatetime2,tdatetime3,tdatetime4,tdatetime5]
32
+
33
+
34
+
35
+ for index, tdate in enumerate(sorted(datetime_list, reverse=True)):
36
+
37
+ if tdate == datetime.datetime.strptime(starget_time, '%Y-%m-%d %H:%M:%S'):
38
+
39
+ print("一番近い直前の日付は{}です。".format(datetime_list[index-1]))
40
+
41
+ print("一番近い直後の日付は{}です。".format(datetime_list[index+1]))
42
+
43
+
44
+
45
+ return
46
+
47
+
48
+
23
- now4 = datetime.datetime.now()
49
+ find_nearest_datetime()
24
50
 
25
51
  ```