6
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python3.9 でのdatetimeの扱いのチートシート的メモ書き

Last updated at Posted at 2021-04-28

Python3.9でdatetimeの扱い方法のチートシート的メモ書き

from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

### 生成 ###

## 現在時刻
zone = ZoneInfo("Asia/Tokyo")
now = datetime.now(zone)
print(f'現在時刻: {now}')

# >>>>>>>>>>>>>>>>>
# 現在時刻: 2021-04-07 11:34:20.971192+09:00
# >>>>>>>>>>>>>>>>>

## 指定時刻
first_day_2021 = datetime(2021, 1, 1, 0, 0, 0, tzinfo=zone)
print(f'指定時刻: {first_day_2021}')

# >>>>>>>>>>>>>>>>>
# 指定時刻: 2021-01-01 00:00:00+09:00
# >>>>>>>>>>>>>>>>>

## unixtimestampからの生成
from_unixtimestamp = datetime.fromtimestamp(0, tz=zone)
print(f'unixtimestampから: {from_unixtimestamp}')

# >>>>>>>>>>>>>>>>>
# unixtimestampから: 1970-01-01 09:00:00+09:00
# >>>>>>>>>>>>>>>>>

### 演算 ###

## 10秒足す
add_10sec = first_day_2021 + timedelta(seconds=10)
print(f'10秒足す: {add_10sec}')

# >>>>>>>>>>>>>>>>>
# 10秒足す: 2021-01-01 00:00:10+09:00
# >>>>>>>>>>>>>>>>>

## 10分引く
minus_10mins = first_day_2021 - timedelta(minutes=10)
print(f'10分引く: {minus_10mins}')

# >>>>>>>>>>>>>>>>>
# 10分引く: 2020-12-31 23:50:00+09:00
# >>>>>>>>>>>>>>>>>

## 1時間足す
add_1hour = first_day_2021 + timedelta(hours=1)
print(f'1時間足す: {add_1hour}')

# >>>>>>>>>>>>>>>>>
# 1時間足す: 2021-01-01 01:00:00+09:00
# >>>>>>>>>>>>>>>>>

## 1日引く
minus_1day = first_day_2021 - timedelta(days=1)
print(f'1日引く: {minus_1day}')

# >>>>>>>>>>>>>>>>>
# 1日引く: 2020-12-31 00:00:00+09:00
# >>>>>>>>>>>>>>>>>

### 文字列出力 ###

## 2021-01-01 00:00:00
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# >>>>>>>>>>>>>>>>>
# 2021-04-07 11:34:20
# >>>>>>>>>>>>>>>>>


## 2021/01/01 00:00:00
now.strftime("%Y/%m/%d %H:%M:%S")
print(now.strftime("%Y/%m/%d %H:%M:%S"))

# >>>>>>>>>>>>>>>>>
# 2021/04/07 11:34:20
# >>>>>>>>>>>>>>>>>

参考

6
13
1

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
6
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?