python时间格式转换--timedelta转换为时分秒 格式
方法一:
先用timedelta.total_seconds(x)将timedelta转换为秒,再用strftime('%H:%M:%S',gmtime(x)))将秒转换为时分秒格式
例:
from time import gmtime
from time import strftime
import pandas as pd
import datetime
from datetime import timedelta
df=pd.read_excel(r'E:\数据源.xlsx')
df=df[~df['审核时间'].isnull()]
df['审核时间']=pd.to_datetime(df['审核时间'])
df['采样时间']=pd.to_datetime(df['采样时间'])
df['时长']=df['审核时间']-df['采样时间']
df['时长']=df['时长'].apply(lambda x:timedelta.total_seconds(x))
df['时长'].map(lambda x:strftime('%H:%M:%S',gmtime(x)))
Output:
以上方法中是先将timedelta转换为秒,然后再利用map(lambda x: strftime('%H:%M:%S',gmtime(x)))将秒转换为时分秒格式
timedelta转换为秒然用到函数:timedelta.total_seconds()
timedelta.total_seconds():此方法的返回类型是一个数字,该数字是该时间段内覆盖的总秒数;
from datetime import time, timedelta
## total_seconds function
x = timedelta(minutes = 2*15)
total = x.total_seconds()
print("Total seconds in 30 minutes:", total)
Output:
Total seconds in 30 minutes: 1800.0
方法二:自定义一个函数
def convert(x):
hours = x.components.hours
minutes = x.components.minutes
seconds = x.components.seconds
return f"{hours}:{minutes}:{seconds}"
df['时长']=df['时长'].apply(convert)
df['时长'].head()
Output:
方法二中,Series.dt.components:返回 Timedeltas 组件的 Dataframe。
s = pd.Series(pd.to_timedelta(np.arange(5), unit='s'))
s
0 0 days 00:00:00
1 0 days 00:00:01
2 0 days 00:00:02
3 0 days 00:00:03
4 0 days 00:00:04
dtype: timedelta64[ns]
s.dt.components
days hours minutes seconds milliseconds microseconds nanoseconds
0 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0
2 0 0 0 2 0 0 0
3 0 0 0 3 0 0 0
4 0 0 0 4 0 0 0
Jasminelee