【问题标题】:Add 24 hours to time in python在python中添加24小时
【发布时间】:2019-07-30 14:14:00
【问题描述】:

需要以 24 小时为单位添加具有“时间”格式值的数据框列。 例如:如果 24 小时加上 10:30:30 的值,那么预期的结果是 34:30:30,下面的代码片段(作为图像添加)生成 '0 days 10:30:30'

enter image description here 谁能指导我不要获得 0days 并获得 24 小时以添加小时值。

【问题讨论】:

标签: python-3.x pandas dataframe


【解决方案1】:

示例

N = 10
np.random.seed(2019)
rng = pd.date_range('2017-04-03 15:30:20', periods=N, freq='13.3T')
df = pd.DataFrame({'vstime': np.abs(np.random.choice(rng, size=N) - 
                                 np.random.choice(rng, size=N))})

print (df)
    vstime
0 00:39:54
1 00:13:18
2 01:06:30
3 01:19:48
4 00:13:18
5 00:13:18
6 01:46:24
7 01:06:30
8 00:39:54
9 01:46:24

您的代码使用to_timedelta 并添加Timedelta

df['vstime'] = pd.to_timedelta(df['vstime']) + pd.Timedelta(24, unit='h') 

原生不支持格式化timedelta,所以需要自定义函数:

def f(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return ('{}:{:02d}:{:02d}').format(int(hours), int(minutes), int(seconds)) 

df['duration'] = df['vstime'].apply(f)
print (df)
           vstime  duration
0 1 days 00:39:54  24:39:54
1 1 days 00:13:18  24:13:18
2 1 days 01:06:30  25:06:30
3 1 days 01:19:48  25:19:48
4 1 days 00:13:18  24:13:18
5 1 days 00:13:18  24:13:18
6 1 days 01:46:24  25:46:24
7 1 days 01:06:30  25:06:30
8 1 days 00:39:54  24:39:54
9 1 days 01:46:24  25:46:24

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多