LoginSignup
12
12

More than 5 years have passed since last update.

Pythonでの日付操作のめも

Posted at

ある月の、×曜日の日付を全部とってきたり、ある月のnヶ月後は何年何月かとか計算したかったので調べてみた。
知らなかったけど、月の計算はtimedeltaではできないらしい。

>>> from datetime import datetime
>>> import calendar
>>> now = datetime.strptime('2014-11-1', '%Y-%m-%d')
datetime.datetime(2014, 11, 1, 0, 0)
>>> #任意の月の日曜日の日にちをリストで取得する
>>> [x[calendar.SUNDAY] for x in calendar.monthcalendar(now.year, now.month)]
[2, 9, 16, 23, 30]
>>> # ひと月に4回しかない曜日の場合、リストの先頭値が0になる
>>> [x[calendar.MONDAY] for x in calendar.monthcalendar(now.year, now.month)]
[0, 3, 10, 17, 24]

>>> #月の計算(現在日付のnヶ月前、nヶ月後を計算できる)
>>> import time
>>> datetime.fromtimestamp(time.mktime((now.year,now.month + 2,1,0,0,0,0,0,0)))
datetime.datetime(2015, 1, 1, 0, 0)
>>> datetime.fromtimestamp(time.mktime((now.year,now.month + 15,1,0,0,0,0,0,0)))
datetime.datetime(2016, 2, 1, 0, 0)

>>> # 日にちの計算とかはtimedeltaを使うと簡単
>>> from datetime import timedelta
>>> now + timedelta(days=1)
datetime.datetime(2014, 11, 2, 0, 0)

参考リンク
Pythonでの日付関連処理
月の加減算処理ができない?
8.1. datetime — 基本的な日付型および時間型

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