LoginSignup
0
2

More than 1 year has passed since last update.

文字列の時間を分とか秒へ変換したい

Posted at

やりたいこと

Youtubeのコメントによくある、「5:11 めっちゃおもろいw」のようなコメントから

5:11の部分を持ってきて、秒数などに変換したい。

どうすればいいか

文字列の時間(1:38:30みたいなの)から時、分、秒を取ってくる必要がある。

2:23:11→2時間23分11秒

1:34→1分34秒

同じような表記なのでどこが時で分で秒か?ということを考慮する必要がある。

調べてみると、文字列→時間に変換するには、

strftime(),strptime()を使うことでできるらしい。

使用例:
import datetime
tt = datetime.datetime.strptime('1:23:32', '%H:%M:%S').strftime('%H:%M:%S')
print(tt)

01:23:32

時、分、秒を別々に取得するには
cmt = '2:4:22'
hour = datetime.datetime.strptime(cmt, '%H:%M:%S').strftime('%H')
min = datetime.datetime.strptime(cmt, '%H:%M:%S').strftime('%M')
sec = datetime.datetime.strptime(cmt, '%H:%M:%S').strftime('%S')

print(int(hour) * 60 * 60)
print(int(min) * 60)
print(sec)

このようにすれば、それぞれの秒数を取得できる、

注意点は、文字列を格納しているcmtの表記が分:秒であるときはエラーになるので、
分:秒ように分岐させる必要あり。

0
2
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
0
2