0
0

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 3 years have passed since last update.

Pythonのdatetimeモジュールで日時を取得するサンプル

Posted at

Pythonのdatetimeモジュールで日時を取得するサンプル

はじめに

コードを書いていて日時を使用する場面が出てくるかと思います。
そのときに私がほしいと思う、フォーマットと表示のサンプルを書きました。
解説はしていなくて、フォーマットと表示の羅列のみです。

環境

  • windows 10
  • Python 3.9.1
  • datetime

コード

import datetime

NOW = datetime.datetime.now()

print(NOW)
print(type(NOW))
# 2021-09-06 18:19:37.079126
# <class 'datetime.datetime'>

print(NOW.year)
print(type(NOW).year)
# 2021
# <attribute 'year' of 'datetime.date' objects>

print(NOW.month)
print(type(NOW.month))
# 9
# <class 'int'>

print(NOW.day)
print(type(NOW.day))
# 6
# <class 'int'>

# 曜日
# 0:月, 1:火, 2:水, 3:木, 4:金, 5:土, 6:日
print(NOW.weekday())
print(type(NOW.weekday()))
# 0
# <class 'int'>

# UTC
print(NOW.utcnow())
print(type(NOW.utcnow()))
# 2021-09-06 09:19:37.079126
# <class 'datetime.datetime'>

print(NOW.strftime("%Y_%m_%d"))
print(type(NOW.strftime("%Y_%m_%d")))
# 2021_09_06
# <class 'str'>

print(NOW.strftime("%Y/%m/%d %H:%M"))
print(type(NOW.strftime("%Y/%m/%d %H:%M")))
# 2021/09/06 18:19
# <class 'str'>

# 一週間前
print(NOW + datetime.timedelta(weeks=-1))
print(type(NOW + datetime.timedelta(weeks=-1)))
# 2021-08-30 18:19:37.079126
# <class 'datetime.datetime'>

# 30日前
print(NOW + datetime.timedelta(days=-30))
# 2021-08-07 18:19:37.079126

# 一時間前
print(NOW + datetime.timedelta(hours=-1))
# 2021-09-06 17:19:37.079126

# 1日と12時間を秒に変換
dt = datetime.timedelta(days=1, hours=12)
print(dt.total_seconds())
print(type(dt.total_seconds()))
# 129600.0
# <class 'float'>

# 3600秒を日時に変換
print(datetime.timedelta(seconds=3600))
print(type(datetime.timedelta(seconds=3600)))
# 1:00:00
# <class 'datetime.timedelta'>

参考

datetime --- 基本的な日付型および時間型 — Python 3.9.4 ドキュメント

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?