LoginSignup
22
24

More than 5 years have passed since last update.

Pythonで時刻を消して日付だけにしたいとき

Last updated at Posted at 2017-10-18

はじめに

2017/10/19 10:54:29 みたいな日付と時刻があるデータを 2017/10/19 みたいな日付だけのデータにしたいとき、少し詰まったのでメモとしてここに残したいと思います。

strptime()とstrftime()を使う

import datetime

date = '2017/10/19 10:54:29'
new_date = datetime.datetime.strptime(date, '%Y/%m/%d %H:%M:%S').strftime('%Y/%m/%d')
new_date #=> '2017/10/19'

追記

下記のコメントより、もっと手軽に分割する方法もあります。

date = '2017/10/19 10:54:29'
new_date, new_time = date.split()
new_date #=> '2017/10/19'

参考

AttributeError: 'str' object has no attribute 'strftime'

22
24
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
22
24