LoginSignup
5
2

More than 5 years have passed since last update.

pythonで3ヶ月前の1日を取得

Last updated at Posted at 2018-06-06

苦手だったpythonでの日時操作に少し慣れてきたのでメモ。timedeltaではmonthの加減ができないらしく、import timedatetime.fromtimestamp(time.mktime(hogehoge))つかってる記事をたくさん見かけたが、以下でいけるんじゃないの?

と、その前に超基本のnow()とtoday()

import datetime

today = datetime.datetime.today()
print today.year # 2017
print today.month # 8
print today.day # 10

now = datetime.datetime.now()
print now.hour # 8
print now.minute # 44
print now.second # 55
pirnt now.microsecond # 665

もっと基本: 日時オブジェクトの作成

import datetime

d = datetime.datetime(2017, 8, 10)
print d # 2017-08-10 00:00:00

t = datetime.time(12, 33, 59)
print t # 12:33:59

これも基本: timedelta

timedeltaオブジェクトはdatetimeオブジェクトの差で生成される。日、秒、マイクロ秒のデータが内部的に保存されており、days, seconds, microsecondsメソッドを使用することにより情報を取得することができる。年や月は保存されていない。

import datetime

d1 = datetime.datetime(2017, 8, 10)
d2 = datetime.datetime(2017, 8, 1)
diff = d1 - d2
print diff.days # 9

dt = datetime.timedelta(days=9)
d3 = d1 - dt
print d3 # 2017-08-01

本題: 3ヶ月前の初日を取得

today = datetime.datetime.today()ってしといてdatetime.datetime(today.year, today.month - 3, 1)でええんちゃうん。

import datetime

today = datetime.datetime.today()
three_months_ago = datetime.datetime(today.year, today.month - 3, 1)

こっちのほうが簡単だと思うんだけどな〜

おまけ: strftime

datetimeオブジェクトを文字列にする場合にstrftimeを使うみたいだけど0が省略されないので嫌だ。

import datetime

today = datetime.datetime.today()

print today.strftime('%y年%m月%d日' # 2017年08月10日

print str(today.year) + '年' + str(today.month) + '月' + str(today.day) + '日' # 2017年8月10日

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