LoginSignup
1
0

More than 5 years have passed since last update.

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

Posted at

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型で日時の引き算

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0