将时间四舍五入到最接近的秒 \- Python

新手上路,请多包涵

我有一个包含超过 500 000 个日期和时间戳的大型数据集,如下所示:

 date        time
2017-06-25 00:31:53.993
2017-06-25 00:32:31.224
2017-06-25 00:33:11.223
2017-06-25 00:33:53.876
2017-06-25 00:34:31.219
2017-06-25 00:35:12.634

如何将这些时间戳四舍五入到最接近的秒数?

我的代码如下所示:

 readcsv = pd.read_csv(filename)
log_date = readcsv.date
log_time = readcsv.time

readcsv['date'] = pd.to_datetime(readcsv['date']).dt.date
readcsv['time'] = pd.to_datetime(readcsv['time']).dt.time
timestamp = [datetime.datetime.combine(log_date[i],log_time[i]) for i in range(len(log_date))]

所以现在我将日期和时间组合成一个列表 datetime.datetime 对象,如下所示:

 datetime.datetime(2017,6,25,00,31,53,993000)
datetime.datetime(2017,6,25,00,32,31,224000)
datetime.datetime(2017,6,25,00,33,11,223000)
datetime.datetime(2017,6,25,00,33,53,876000)
datetime.datetime(2017,6,25,00,34,31,219000)
datetime.datetime(2017,6,25,00,35,12,634000)

我从这里去哪里? df.timestamp.dt.round('1s') 功能似乎不起作用?同样在使用 .split() 秒和分钟超过 59 时我遇到了问题

非常感谢

原文由 Jetman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 503
2 个回答

使用 for loopstr.split()

 dts = ['2017-06-25 00:31:53.993',
       '2017-06-25 00:32:31.224',
       '2017-06-25 00:33:11.223',
       '2017-06-25 00:33:53.876',
       '2017-06-25 00:34:31.219',
       '2017-06-25 00:35:12.634']

for item in dts:
    date = item.split()[0]
    h, m, s = [item.split()[1].split(':')[0],
               item.split()[1].split(':')[1],
               str(round(float(item.split()[1].split(':')[-1])))]

    print(date + ' ' + h + ':' + m + ':' + s)

2017-06-25 00:31:54
2017-06-25 00:32:31
2017-06-25 00:33:11
2017-06-25 00:33:54
2017-06-25 00:34:31
2017-06-25 00:35:13
>>>

你可以把它变成一个函数:

 def round_seconds(dts):
    result = []
    for item in dts:
        date = item.split()[0]
        h, m, s = [item.split()[1].split(':')[0],
                   item.split()[1].split(':')[1],
                   str(round(float(item.split()[1].split(':')[-1])))]
        result.append(date + ' ' + h + ':' + m + ':' + s)

    return result

测试功能:

 dts = ['2017-06-25 00:31:53.993',
       '2017-06-25 00:32:31.224',
       '2017-06-25 00:33:11.223',
       '2017-06-25 00:33:53.876',
       '2017-06-25 00:34:31.219',
       '2017-06-25 00:35:12.634']

from pprint import pprint

pprint(round_seconds(dts))

['2017-06-25 00:31:54',
 '2017-06-25 00:32:31',
 '2017-06-25 00:33:11',
 '2017-06-25 00:33:54',
 '2017-06-25 00:34:31',
 '2017-06-25 00:35:13']
>>>

由于您似乎使用的是 Python 2.7,要删除任何尾随零,您可能需要更改:

str(round(float(item.split()[1].split(':')[-1])))

str(round(float(item.split()[1].split(':')[-1]))).rstrip('0').rstrip('.')

我刚刚在 repl.it 上用 Python 2.7 尝试了这个函数,它按预期运行。

原文由 srikavineehari 发布,翻译遵循 CC BY-SA 3.0 许可协议

在没有任何额外包的情况下,可以使用以下简单函数将日期时间对象四舍五入到最接近的秒:

 import datetime as dt

def round_seconds(obj: dt.datetime) -> dt.datetime:
    if obj.microsecond >= 500_000:
        obj += dt.timedelta(seconds=1)
    return obj.replace(microsecond=0)

原文由 derpedy-doo 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题