IIUC,您可以使用创建一个以“00:00”为时间的日期时间,并将小时添加为
timedelta
:
from datetime import date, time, datetime, timedelta
from zoneinfo import ZoneInfo
def process_30hour(d: date, t: str):
h, m = map(int, t.split(':')) # assumes format 'HH:MM' for t
return (datetime.combine(d, time(), ZoneInfo('Japan'))
+ timedelta(hours=h, minutes=m))
process_30hour(date(2024, 12, 20), '25:25')
输出:
datetime.datetime(2024, 12, 21, 1, 25, tzinfo=zoneinfo.ZoneInfo(key='Japan'))
同样的逻辑也可以在pandas中向量使用:
df = pd.DataFrame({'date': ['2024-12-20 20:25', '2024-12-20 25:25']})
# split string
tmp = df['date'].str.split(expand=True)
# convert to datetime/timedelta, combine
df['datetime'] = pd.to_datetime(tmp[0]) + pd.to_timedelta(tmp[1]+':00')
为了好玩,作为一句俏皮话:
df['datetime'] = (df['date'].add(':00')
.str.split(expand=True)
.astype({0: 'datetime64[ns]',
1: 'timedelta64[ns]'})
.sum(axis=1)
)
输出:
date datetime
0 2024-12-20 20:25 2024-12-20 20:25:00
1 2024-12-20 25:25 2024-12-21 01:25:00