LoginSignup
1
0

More than 5 years have passed since last update.

Python 秒単位の定義値をN分やN時間で書きたいとき

Last updated at Posted at 2018-12-11

課題

秒単位の定義値をN分やN時間で書きたいとき

XXX_SECONDS = 12 * 60 * 60  # 12 hours
YYY_SECONDS = 1 * 60  # 1 minute
ZZZ_SECONDS = (1 * 60 * 60) + (30 * 60)  # 1 hour 30 minutes

みたいに書いていたけど、値を書き換えるときにミスしそうな予感があった。

解決方法

timedelta.total_seconds()を使って書くと、ちょっと直感的になった。好みの問題かもですが。
(timedelta.total_seconds()が使えるのはpython3.2以上)

from datetime import timedelta

XXX_SECONDS = int(timedelta(hours=12).total_seconds())
YYY_SECONDS = int(timedelta(minutes=1).total_seconds())
ZZZ_SECONDS = int(timedelta(hours=1, minutes=30).total_seconds())

補足

timedelta.total_seconds()ではなく
timedelta.secondsを使うと「両端値を含む 0 から 86399 の間」なので
24時間以上の値で目的の通り動かない

timedelta(hours=24).seconds # 0 NG

int(timedelta(hours=24).total_seconds()) # 86400 OK

参考

1
0
2

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