Python で文字列を日時データに変換,時分秒の切り捨て,日時の比較,日時データの数え上げ
前準備
Python の準備(Windows,Ubuntu 上)
- Windows での Python 3.10,関連パッケージ,Python 開発環境のインストール(winget を使用しないインストール): 別ページ »で説明
- Ubuntu では,システム Pythonを使うことができる.Python3 開発用ファイル,pip, setuptools のインストール: 別ページ »で説明
【サイト内の関連ページ】
- Python のまとめ: 別ページ »にまとめ
- Google Colaboratory の使い方など: 別ページ »で説明
【関連する外部ページ】 Python の公式ページ: https://www.python.org/
文字列を datetime.datetime 型に変換
"2017-7-1 11:38:24"
from datetime import datetime as dt
from datetime import timezone
from datetime import timedelta
# 文字列を datetime.datetime 型に変換
def to_datetime(x):
return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" )
x = to_datetime("2020-06-30 13:00:00 +09:00")
print(x)
print(x.tzinfo)

秒,分,時の切り捨て
- その日の 0時 0分の取得。結果は datetime.datetime 型で得る
from datetime import datetime as dt from datetime import timezone from datetime import timedelta # 文字列を datetime.datetime 型に変換 def to_datetime(x): return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" ) # その日の 0時 0分. パラメータは datetime.datetime 型 def first_of_day(x): return dt(x.year, x.month, x.day, tzinfo=x.tzinfo) x = to_datetime("2020-06-30 13:00:00 +09:00") print(first_of_day(x)) print(first_of_day(x).tzinfo)
- その日の 0時 0分から、何秒経過した
from datetime import datetime as dt from datetime import timezone from datetime import timedelta import time # 文字列を datetime.datetime 型に変換 def to_datetime(x): return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" ) # その日の 0時 0分. パラメータは datetime.datetime 型 def first_of_day(x): return dt(x.year, x.month, x.day, tzinfo=x.tzinfo) # その日の 0時 0分から、何秒経過したか def elapsed(x): # unixtime の引き算 return x.timestamp() - first_of_day(x).timestamp() x = to_datetime("2020-7-1 11:38:24 +09:00") # 41904.0 が表示される print( elapsed(x) )
- 「分の始め」から何秒経過したを表示
from datetime import datetime as dt from datetime import timezone from datetime import timedelta import time # 文字列を datetime.datetime 型に変換 def to_datetime(x): return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" ) # 秒以下を切り捨て. パラメータは datetime.datetime 型 def first_of_minute(x): return dt(x.year, x.month, x.day, x.hour, x.minute, tzinfo=x.tzinfo) x = to_datetime("2020-7-1 11:38:24 +09:00") print(x) print(x.timestamp() - first_of_minute(x).timestamp())
日時の引き算
- ある日時の 60 秒前
from datetime import datetime as dt from datetime import timezone from datetime import timedelta import time # 文字列を datetime.datetime 型に変換 def to_datetime(x): return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" ) # 秒数を指定 def past_time(x, delta): return x - timedelta(seconds=delta) x = to_datetime("2020-7-1 11:38:24 +09:00") print(x) print(past_time(x, 60))
日時の比較
- グローバル変数 basetime で設定された日時以降なら true
basetime = to_datetime("2020-06-30 09:00:00 +09:00") def time_selection(x): return x.timestamp() > basetime.timestamp() x = to_datetime("2020-7-1 11:38:24 +09:00") print(x) print(time_selection(x)) y = to_datetime("2020-6-29 11:38:24 +09:00") print(y) print(time_selection(y))
日時の数え上げ
次のようなデータがあるとする. 日時を 300秒ごとに区切って value_counts を使って数え上げを行う。
import pandas as pd
from datetime import datetime as dt
from datetime import timezone
from datetime import timedelta
# 文字列を datetime.datetime 型に変換
def to_datetime(x):
return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" )
m1 = pd.DataFrame([
[1, "2020-7-1 11:38:00 +09:00"],
[2, "2020-7-1 11:38:00 +09:00"],
[4, "2020-7-1 11:39:00 +09:00"],
[5, "2020-7-1 11:40:00 +09:00"],
[6, "2020-7-1 11:40:00 +09:00"],
[7, "2020-7-1 11:40:00 +09:00"]
],
columns=['id', 'datetime'])
# その日の 0時 0分. パラメータは datetime.datetime 型
def first_of_day(x):
return dt(x.year, x.month, x.day, tzinfo=x.tzinfo)
# その日の 0時 0分から、何秒経過したか
def elapsed(x):
# unixtime の引き算
return x.timestamp() - first_of_day(x).timestamp()
x = ( m1.datetime.map(to_datetime).map(elapsed) // 300 ) * 300
print(x.value_counts(sort=True, ascending=True))

import pandas as pd
from datetime import datetime as dt
from datetime import timezone
from datetime import timedelta
import time
# 文字列を datetime.datetime 型に変換
def to_datetime(x):
return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" )
# その日の 0時 0分. パラメータは datetime.datetime 型
def first_of_day(x):
return dt(x.year, x.month, x.day, tzinfo=x.tzinfo)
# その日の 0時 0分から、何秒経過したか
def elapsed(x):
# unixtime の引き算
return x.timestamp() - first_of_day(x).timestamp()
def compate_by_date(base):
return (lambda x: time.mktime(first_of_day(to_datetime(x)).timetuple()) == time.mktime(first_of_day(to_datetime(base)).timetuple()))
print(compate_by_date("2020-07-11 0:0:0 +09:00")("2020-07-11 10:0:0 +09:00"))
print(compate_by_date("2020-07-11 0:0:0 +09:00")("2020-07-12 10:0:0 +09:00"))

import pandas as pd
from datetime import datetime as dt
from datetime import timezone
from datetime import timedelta
# 文字列を datetime.datetime 型に変換
def to_datetime(x):
return dt.strptime(x, "%Y-%m-%d %H:%M:%S %z" )
# その日の 0時 0分. パラメータは datetime.datetime 型
def first_of_day(x):
return dt(x.year, x.month, x.day, tzinfo=x.tzinfo)
# その日の 0時 0分から、何秒経過したか
def elapsed(x):
# unixtime の引き算
return x.timestamp() - first_of_day(x).timestamp()
def compate_by_date(base):
return (lambda x: time.mktime(first_of_day(to_datetime(x)).timetuple()) == time.mktime(first_of_day(to_datetime(base)).timetuple()))
m2 = pd.DataFrame([
[1, "2020-7-1 11:38:00 +09:00"],
[2, "2020-7-1 11:38:00 +09:00"],
[4, "2020-7-1 11:39:00 +09:00"],
[5, "2020-7-1 11:40:00 +09:00"],
[6, "2020-7-2 3:10:00 +09:00"],
[7, "2020-7-2 3:10:00 +09:00"]
],
columns=['id', 'datetime'])
print('----')
print(m2[ m2.datetime.map(compate_by_date("2020-07-1 0:0:0 +09:00")) ])
print('----')
print(m2[ m2.datetime.map(compate_by_date("2020-07-2 0:0:0 +09:00")) ])
