from datetime import datetime
str_datetime = "2020-10-26 17:22:51"
# 文字列から datetime に変換
dt = datetime.strptime(str_datetime '%Y-%m-%d %H:%M:%S')
# datetime から unixtime に変換
dt.timestamp()
# unixtime から datetime に変換
dt = datetime.fromtimestamp(ut)
# datetime から文字列に変換
dt.strftime('%Y-%m-%d %H:%M:%S')
現在の日時を取得する
# curr_date_time.py
from datetime import datetime
curr_datetime = datetime.now()
curr_date = curr_datetime.date()
curr_time = curr_datetime.time()
print(f"The current date time is {curr_datetime}")
print(f"Today's date is {curr_date}")
print(f"Current time is {curr_time}")
日付と時刻をそのコンポーネントに分割する
# curr_date_time.py
from datetime import datetime
curr_datetime = datetime.now()
curr_year = curr_datetime.year
curr_month = curr_datetime.month
curr_day = curr_datetime.day
curr_hour = curr_datetime.hour
curr_min = curr_datetime.minute
curr_sec = curr_datetime.second
print(f"The current date time is {curr_datetime}")
print(f"The year is {curr_year}")
print(f"The month is {curr_month}")
print(f"The day is {curr_day}")
print(f"Current hour of the day is {curr_hour}")
print(f"Current minute of the day is {curr_min}")
print(f"Current seconds are {curr_sec}")
手動の日付と時刻オブジェクトの作成
# new_date_time.py
from datetime import date
req_date = date(year=2017,
month=1,
day=1)
print(req_date)
タイムデルタ
timedeltaオブジェクトは、二つの日付や時刻の差を提供します。一般的な構文は次のようになります。
今から2日3時間15分先の日時は?
# new_date_time.py
from datetime import datetime,timedelta
# Get the current date and time
curr_date_time = datetime.now()
print(curr_date_time)
time_diff = timedelta(days=2,
hours=3,
minutes=15)
# Add time diff to the current time
req_date_time = curr_date_time + time_diff
print(req_date_time)
2019年6月1日午前9時の1週間前と3日前の日時は?
# new_date_time.py
from datetime import datetime,timedelta
# Get the base date and time
base_date_time = datetime(year=2019,
month=6,
day=1,
hour=9)
print(base_date_time)
time_diff = timedelta(weeks=-1,
days=-3)
# Subtract time diff to the current time
req_date_time = base_date_time + time_diff
print(req_date_time)
タイムゾーンの処理
# new_date_time.py
from datetime import datetime
dt_object = datetime(year=2019,
month=1,
day=1)
print(dt_object.tzinfo)
これは、pythondatetimeモジュールの欠点の1つです。Python datetimeモジュールのクラスまたはメソッドを使用して、datetimeオブジェクトにタイムゾーンを認識させる方法はありません。それはあなたがそれを達成できないという意味ではありません。pytzライブラリを使用して、アプリケーションにタイムゾーン情報を追加できます。
では、正しいタイムゾーン名を見つける方法は?
1. すべてのタイムゾーンデータベース名のリストについては、ここを参照できます。
2. pytzライブラリを使用して、すべてのタイムゾーンのリストを作成することもできます。
# tz_list.py
import pytz
print(pytz.all_timezones)
上記の方法のいずれかを使用すると、要件に合った正しいタイムゾーンを選択できます。タイムゾーンの名前を取得したら、それをアプリケーションに含めることができます。
# tz_info.py
from datetime import datetime
import pytz
dt = datetime.now()
readable_dt = datetime.strftime(dt, "%d/%m/%Y, %H:%M:%S")
print(readable_dt)
tz_India = pytz.timezone("Asia/Calcutta")
dt_India = datetime.now(tz_India)
readable_dt_India = datetime.strftime(dt_India, "%d/%m/%Y, %H:%M:%S")
print(readable_dt_India)
上記のコードスニペットを実行すると、現在の日時とインドの現在の日時の違いを確認できます。