LoginSignup
0
2

More than 1 year has passed since last update.

Pythonによる日付処理

Posted at

SageMakerからデータベースにクエリを投げる際にデータ年月日やテーブル名に日付を指定する必要が多々ある。
その際に目当てのテーブル名や日付のカラムの形式、データ期間の指定において、日付を変数化して操作したい場合があるため、備忘メモとしてここにまとめる。

形式の変換(日付型→文字列型)

from datetime import date

TARGET_DATE = date(2022, 9, 29)
print(type(TARGET_DATE))
print(TARGET_DATE)

<class 'datetime.date'>
2022-09-29

# 形式の変換(文字列)
Ymd = TARGET_DATE.strftime('%Y%m%d')
hyphen = TARGET_DATE.strftime('%Y-%m-%d')
slash = TARGET_DATE.strftime('%Y/%m/%d')
Ym = TARGET_DATE.strftime('%Y%m')

print(type(Ymd), Ymd)
print(type(hyphen), hyphen)
print(type(slash), slash)
print(type(Ym), Ym)

<class 'str'> 20220929
<class 'str'> 2022-09-29
<class 'str'> 2022/09/29
<class 'str'> 202209

形式の変換(文字列型→日付型)

# 文字列型から日付型に変換
str_TARGET_DATE = '2022-09-29'
print(type(str_TARGET_DATE))
print(str_TARGET_DATE)

<class 'str'>
2022-09-29

from datetime import datetime

date_TARGET_DATE = datetime.strptime(str_TARGET_DATE, '%Y-%m-%d').date()
print(type(date_TARGET_DATE))
print(date_TARGET_DATE)

<class 'datetime.date'>
2022-09-29

形式の変換(数値型→日付型)

# 数値型から日付型に変換
int_TARGET_DATE = 20220929
print(type(int_TARGET_DATE))
print(int_TARGET_DATE)

<class 'int'>
20220929

from datetime import datetime

date_TARGET_DATE = datetime.strptime(str(int_TARGET_DATE), '%Y%m%d').date()
print(type(date_TARGET_DATE))
print(date_TARGET_DATE)

<class 'datetime.date'>
2022-09-29

日付の加算・減算

# 日付の加算・減算(日単位)
from datetime import date
from datetime import timedelta

today = date(2022, 9, 29)
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)

print(yesterday)
print(today)
print(tomorrow)

2022-09-28
2022-09-29
2022-09-30

# 日付の加算・減算(月単位)
from datetime import date
from dateutil.relativedelta import relativedelta

today = date(2022, 9, 29)
next_month = today + relativedelta(months=1)
last_month = today - relativedelta(months=1)

print(last_month)
print(today)
print(next_month)

2022-08-29
2022-09-29
2022-10-29

日付の置換

# 日付の置換(当月の月初日・月末日を取得)
from datetime import date

today = date(2022, 9, 29)
this_month_first_day = today.replace(day=1)
this_month_last_day = today.replace(day=1) + relativedelta(months=1) - timedelta(days=1)

print(this_month_first_day)
print(today)
print(this_month_last_day)

2022-09-01
2022-09-29
2022-09-30

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