Python中最接近的一天的时间戳 [英] Round timestamp to nearest day in Python

查看:100
本文介绍了Python中最接近的一天的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.7.2中,我从历元中得到秒数:

In Python 2.7.2 I am getting the seconds since epoch using:

sec_since_epoch =(date_obj - datetime(1970,1,1 ,0,0))。total_seconds()

现在我想将这几秒轮到最近的一天,例如如果:

Now I want to round these seconds to the nearest day e.g. if:

datetime.fromtimestamp(sec_since_epoch)

对应于 datetime(2013,12,14,5,0,0)

我想要新的时间戳对应于 datetime(2013,12,14,0,0,0)

I want the new timestamp to correspond to datetime(2013, 12, 14, 0, 0, 0)

我知道丑陋的方式但是有一种优雅的方式吗?

I know the ugly way of doing it, but is there an elegant way ?

推荐答案

当然,只需转换 datetime to a date first:

Sure, just convert the datetime to a date first:

sec_since_epoch = (date_obj.date() - date(1970, 1, 1)).total_seconds()

当然 date() truncates。如果要在中午之后或之后四舍五入,只需在截断前添加12个小时,或在同一天检查日期是否为> =中午,如果是,则添加一天(请注意,这些可以做不同的事情DST边界天数),或任何您要舍弃的规则。

Of course date() truncates. If you want to round up if on or after noon, etc., just add 12 hours before truncating, or check whether the date is >= noon on the same day and if so add a day (note that these can do different things on DST boundary days), or whatever rule you want to round by.

这篇关于Python中最接近的一天的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆