Help us understand the problem. What is going on with this article?

datetimeで計算したときの値の取り出し方

More than 1 year has passed since last update.

datetime.now()を使用したときに秒の値だけを取り出す方法

from datetime import datetime
n = datetime.now() # datetime.datetime(2018, 3, 28, 18, 2, 31, 658000)
print n.second # 31

時間差を計算したいとき

from datetime import datetime

n = datetime.now() # datetime.datetime(2018, 3, 28, 18, 29, 19, 71000)
p = datetime.strptime('2018-03-28 18:30:05', '%Y-%m-%d %H:%M:%S')
t = p - n 
print t # datetime.timedelta(0, 45, 929000)

計算した時間から秒の値だけを取り出したいときには

print t.second

するとこのようなエラーが…

AttributeError: 'datetime.timedelta' object has no attribute 'second

あるぇー

計算した場合はこうやって取り出すのだそう

print t.seconds # 45

参考

datetime型で日時の引き算

K_M95
IBM Champion 2020 / LINE API Expert 2020
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away