Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
日付に関する関数いくつか
import datetime
today = datetime.date.today()
## 今日
print today
"""
2015-07-18
"""
##日付の計算
#単位を設定。日付の差、などは、timedelaオブジェクト。
one_day = datetime.timedelta(days=1)
print one_day
"""
1 day, 0:00:00
"""
# 設定したone dayを使って昨日の日付取得
today - one_day
today = str(today)
print today
"""
2015-07-18
"""
## テキストフォーマットを指定した形でアウトプット
date_string = '2004-10-16'
date_format = '%Y-%m-%d'
#strptime は、
d = datetime.datetime.strptime(today,date_format)
# strftimeがフォーマット指定
print d.strftime('%Y-%m-%d')
"""
2015-07-18
"""
## 日付の差を計算
date1 = (1994,5,16)
date2 = (2015,7,18)
d1 = datetime.date(*date1)
d2 = datetime.date(*date2)
diff = d2 - d1
diff_days = datetime.timedelta(diff.days)
print diff_days
"""
7733 days, 0:00:00
"""
# daysメソッドを使って、日付のところだけ取り出せる
print diff_days.days
"""
7733
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.