0
1

何日前の日付をPythonで調べる

Posted at

今日の○日前はいつ?

"何日前" という情報から、それが何月何日なのかをPythonで調べてみた。
Excelの方が早いじゃん、とか言わないでください。コマンドラインで起動できるPythonを使えばExcelの起動を待っている間に答えが出る!かな?(笑)

対話モードを起動して、

Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun  6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> t = datetime.datetime.today()
>>> t
datetime.datetime(2024, 7, 15, 12, 14, 35, 98633)
>>> t - datetime.timedelta(days=15)
datetime.datetime(2024, 6, 30, 12, 14, 35, 98633)
>>> t - datetime.timedelta(days=100)
datetime.datetime(2024, 4, 6, 12, 14, 35, 98633)
>>>

datetime.datetimeの括弧の中はdatetime.datetime(年, 月, 日, 時, 分, 秒, マイクロ秒)を表しているので、今日(2024年7月15日)の15日前は6月30日、100日前は4月6日

>>> str(t - datetime.timedelta(days=100))
'2024-04-06 12:14:35.098633'

文字列に変換すると一般的な日時表示になるので、この方が見やすいかも。

0
1
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
0
1