Python の日時変換が覚えられず、毎回ググっていたのでまとめました。
タイムゾーンの指定
1 2 3 4 5 6
| from datetime import datetime from dateutil.tz import tzlocal
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
|
datetime型を文字列型に変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from datetime import datetime from dateutil.tz import tzlocal
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
str_datetime: str = now.strftime('%Y-%m-%d') print(str_datetime) # 結果: '2022-01-09'
str_datetime: str = now.strftime('%Y-%m-%d %H:%M:%S') print(str_datetime) # 結果: '2022-01-09 17:22:04'
|
文字列型をdatetime型に変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from datetime import datetime from dateutil.tz import tzlocal import calendar
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
str_datetime: str = now.strftime('%Y-%m-%d %H:%M:%S') print(str_datetime) # 結果: '2022-01-09 17:22:04'
dt: datetime = datetime.strptime(str_datetime, '%Y-%m-%d %H:%M:%S') print(dt) # 結果: 2022-01-09 17:22:04
|
この場合、タイムゾーンが設定されない。
datetime型をタイムスタンプ(int型)に変換
秒までのタイムスタンプ
1 2 3 4 5 6 7 8 9 10 11
| from datetime import datetime from dateutil.tz import tzlocal import calendar
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
timestamp: int = calendar.timegm(now.utctimetuple()) print(timestamp) # 結果: 1641716524
|
Webサービス を使うと、簡単にタイムスタンプを日時に変換できる。
ミリ秒までのタイムスタンプ
10桁のタイムスタンプは秒までしか持っていないので、ミリ秒のタイムスタンプが欲しい場合は 1000倍するとよい。
1 2 3 4 5 6 7 8 9 10 11
| from datetime import datetime from dateutil.tz import tzlocal import calendar
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
timestamp: int = calendar.timegm(now.utctimetuple())*1000 print(timestamp) # 結果: 1641716524000
|
タイムスタンプ(int型)をdatetime型に変換
秒までのタイムスタンプ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from datetime import datetime from dateutil.tz import tzlocal import calendar
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
timestamp: int = calendar.timegm(now.utctimetuple()) print(timestamp) # 結果: 1641716524
dt: datetime = datetime.fromtimestamp(timestamp) print(dt) # 結果: 2022-01-09 17:22:04
|
ミリ秒までのタイムスタンプ
ミリ秒のタイムスタンプの場合は、0.001倍してから変換する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from datetime import datetime from dateutil.tz import tzlocal import calendar
now: datetime = datetime.now(tz=tzlocal()) print(now) # 結果: 2022-01-09 17:22:04.652831+09:00
timestamp: int = calendar.timegm(now.utctimetuple())*1000 print(timestamp) # 結果: 1641716524000
dt: datetime = datetime.fromtimestamp(timestamp*0.001) print(dt) # 結果: 2022-01-09 17:22:04
|
おわりに
とりあえず思いついただけ記載しました。
足りなければ追記します。