23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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()を使う

.py
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'

追記

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

.py
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'

23
23
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
23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?