从 datetime.time 对象获取总秒数

Obtaining total seconds from a datetime.time object

我有一个 datetime.time 对象 02:00:00 我想将它转换为总秒数,应该是 7200 秒。

您可以将时间与参考日期结合起来得到一个日期时间对象。如果您随后减去该参考日期,您将得到一个 timedelta 对象,您可以从中获取 total_seconds:

from datetime import datetime, time

t = time(2,0,0)

ts = (datetime.combine(datetime.min, t) - datetime.min).total_seconds()

print(ts)
# 7200.0

对于 pandas,我将使用时间对象列(系列)的字符串表示形式并将其转换为 timedelta 数据类型 - 然后允许您使用 dt 访问器来获取总秒数:

import pandas as pd

df = pd.DataFrame({'time': [time(2,0,0)]})

df['totalseconds'] = pd.to_timedelta(df['time'].astype(str)).dt.total_seconds()

# df['totalseconds']
# 0    7200.0
# Name: totalseconds, dtype: float64

您可以使用日期时间库进行计算

def time_in_ms():
    from datetime import datetime
    now = datetime.now()
    time_arr = now.strftime("%H:%M:%S").split(":")
    total_time = (int(time_arr[0]) * 3600) + (int(time_arr[1]) * 60) +(int(time_arr[2]))
    return total_time

试试这个方法;参数 'time' 必须采用 hh:mm:ss

格式
def convert_to_seconds(time):
    # Separate all symbols of 'time'
    separated = list(time)
    
    # Delete all ':' symbols
    for i in separated:
        if i == ':':
            separated.remove(i)
    
    # Join the elements of the list together two by two
    separated[0] = separated[0] + separated[1]
    separated[1] = separated[2] + separated[3]
    separated[2] = separated[4] + separated[5]
    
    # Delete the last 3 elements of the list that are useless now
    for count in range(3):
        del l[3]
    
    # Convert to integers
    for i in separated:
        separated[separated.index(i)] = int(i)

    # Calculate seconds
    seconds = 0
    seconds += separated[0] * 3600
    seconds += separated[1] * 60
    seconds += separated[2]

    return seconds

和之前的方法一样长了点,但是理解起来简单了点。