メインコンテンツまでスキップ

pythonでの日付の扱い方

pythonでの日付の取得、タイムゾーンの扱い、日付フォーマット等のサンプルコードです。

import

from datetime import timezone,timedelta,datetime

日付の扱い一式


# タイムゾーン定義
UTC = timezone(timedelta(hours=0), 'UTC')
EST = timezone(timedelta(hours=-5), 'EST')
JST = timezone(timedelta(hours=+9), 'JST')

# 現在時刻取得
now = datetime.now(JST)

# 日付フォーマット
print("now:" + now.strftime("%Y/%m/%d %H:%M:%S"))
print("now(UTC):" + now.astimezone(UTC).strftime("%Y/%m/%d %H:%M:%S"))
print("now(EST):" + now.astimezone(EST).strftime("%Y/%m/%d %H:%M:%S"))

# 日付計算
another_time = now + timedelta(minutes=2)
print("before_time:" + another_time.strftime("%Y/%m/%d %H:%M:%S"))

# 日付文字列"YYYYMMDD_HHMMSS"取得
another_ymd_hms = another_time.strftime("%Y%m%d_%H%M%S")
print("another_ymd_hms:" + another_ymd_hms)
# print(another_ymd_hms[0:4])
# print(another_ymd_hms[4:6])
# print(another_ymd_hms[6:8])
# print(another_ymd_hms[9:11])
# print(another_ymd_hms[11:13])
# print(another_ymd_hms[13:15])

# datetimeの生成(timezone指定)
another_time_2 = datetime(year=int(another_ymd_hms[0:4])
,month=int(another_ymd_hms[4:6])
,day=int(another_ymd_hms[6:8])
,hour=int(another_ymd_hms[9:11])
,minute=int(another_ymd_hms[11:13]),tzinfo=JST)
print("another_time_2:" + another_time_2.strftime("%Y/%m/%d %H:%M:%S"))

# UNIX時間(協定世界時 (UTC) での1970年1月1日午前0時0分0秒からの経過秒数)取得
timestamp_now = datetime.now(JST).timestamp()

# UNIX時間からのdatetime変換
datetime_now = datetime.fromtimestamp(timestamp_now)

本記事へのリンク

test.png

https://docs.saurus12.com/python/date

👇参考URL

pythonでの日付の扱い方

更新日:2024年02月04日

ITとソフトウェアの人気オンラインコースHP Directplus -HP公式オンラインストア-