我在下面有以下代码。
我想将TIME整理到最接近的30分钟。例如:中午12:00或下午12:30等等。
EASTERN_NOW = timezone.localtime(timezone.now() + timedelta(minutes=30))
TIME = datetime.time(EASTERN_NOW.time().hour, EASTERN_NOW.time().minute).strftime(
VALID_TIME_FORMATS[2])
提前致谢
答案 0 :(得分:16)
将向上舍入到最接近的30分钟:
#!/usr/bin/env python3
from datetime import datetime, timedelta
def ceil_dt(dt, delta):
return dt + (datetime.min - dt) % delta
now = datetime.now()
print(now)
print(ceil_dt(now, timedelta(minutes=30)))
The formula is suggested by @Mark Dickinson (for a different question)
2015-09-22 19:08:34.839915
2015-09-22 19:30:00
注意:如果输入是时区感知的日期时间对象,例如EASTERN_NOW
,那么如果要保留舍入的本地时间并附加正确的tzinfo,则应调用timezone.make_aware(rounded_dt.replace(tzinfo=None))
,否则如果舍入越过DST边界,您可能会得到错误的时区信息。或者为避免本地时间不明确,请手动拨打.localize()
:
localize = getattr(rounded_dt.tzinfo, 'localize', None)
if localize:
rounded_dt = localize(rounded_dt.replace(tzinfo=None),
is_dst=bool(rounded_dt.dst()))
答案 1 :(得分:2)
>>> from dateutil.rrule import rrule, MINUTELY
>>> import datetime
>>> import bisect
>>> times = list(rrule(MINUTELY,interval=30,dtstart=datetime.date.today(),count=
48))
>>> print times[bisect.bisect(times,datetime.datetime.now())]
2015-09-22 11:00:00
>>>
请注意,此解决方案使用可以与pip install dateutil
一起安装的第三方dateutil库...当然,您可以在没有它的情况下解决它...但它更容易使用它
答案 2 :(得分:2)
您可以将您的分钟数除以30,然后再将其乘以30,得到0分钟,30分钟或60分钟:
date = datetime.datetime(2015, 9, 22, 12, 35)
approx = round(date.minute/30.0) * 30
date = date.replace(minute=0)
date += datetime.timedelta(seconds=approx * 60)
time = date.time()
print(time.strftime('%H:%M'))
# prints '13:30'
我正在使用datetime对象,因为timedelta不适用于时间对象。最后,您可以使用date.time()
获取时间。
答案 3 :(得分:2)
您可以将日期时间输入分开并调整时间
def ajustTime():
from datetime import datetime
mytime= datetime.now().strftime("%Y-%m-%d %H-%M")
m = mytime.split()
hours, mints = m[1].split('-')
if 15 <= int(mints) <= 45:
mints = ':30'
elif int(mints) < 15:
mints = ':00'
elif int(mints) > 45:
mints = ':00'
h = int(hours) + 1
hours = str(h)
print(m[0] + " " + hours + mints)
ajustTime()
<强>输出强>
2015-09-22 15:42:03.587633
2015-09-22 15:30
2015-09-22 15:46:01.956860
2015-09-22 16:00
答案 4 :(得分:1)
这也应该有效,但不确定时区
rounded=time.gmtime(30*60*(round(time.time()/(30*60))))
答案 5 :(得分:1)
向前滚动你可以使用:
#!/usr/bin/env python3
from datetime import datetime, timedelta
def ceil_dt(dt, delta):
return dt + (datetime.min - dt) % delta
now = datetime.now()
print(now)
print(ceil_dt(now, timedelta(minutes=30)))
回到最接近的第30分钟
def rounded_to_the_last_30th_minute_epoch():
now = datetime.now()
rounded = now - (now - datetime.min) % timedelta(minutes=30)
return rounded
答案 6 :(得分:0)
感谢所有输入人员。我用自己的方法解决了这个问题。
min_time = timezone.localtime(timezone.now())
min_time_est = min_time.minute
if min_time_est > 30:
add_mins = 60 - min_time_est
else:
add_mins = 30 - min_time_est
EASTERN_NOW = timezone.localtime(timezone.now() + timedelta(minutes=add_mins))
TIME = datetime.time(EASTERN_NOW.time().hour, EASTERN_NOW.time().minute).strftime(
VALID_TIME_FORMATS[2])
如果其他人有类似的问题。关于'TIME'每30分钟输出一次,例如'下午1:00'或'下午1:30'。
答案 7 :(得分:0)
在不使用第三方库和几行代码的情况下,通过round_mins
四舍五入到最接近的分钟数量。
import datetime
round_mins = 30
now = datetime.datetime.now()
mins = now.minute - (now.minute % round_mins)
print datetime.datetime(now.year, now.month, now.day, now.hour, mins) + datetime.timedelta(minutes=round_mins)
答案 8 :(得分:0)
要向下取整:
或者,换句话说,使用当前分钟中存在的整个间隔数(x),将分钟数替换为该间隔数(x *间隔):
#!/usr/bin/env python3
def floor_dt(dt, interval):
replace = (dt.minute // interval)*interval
return dt.replace(minute = replace, second=0, microsecond=0)
print(datetime.now())
# datetime.datetime(2019, 5, 30, 22, 25, 31, 115901)
print(floor_dt(datetime.now(),30))
# datetime.datetime(2019, 5, 30, 22, 0)
print(datetime.now())
# datetime.datetime(2019, 5, 30, 22, 26, 29, 469555)
print(floor_dt(datetime.now(),10))
# datetime.datetime(2019, 5, 30, 22, 20)
答案 9 :(得分:0)
要四舍五入,可以使用这两个功能。您无需计算秒数或使用数学模块。
from datetime import timedelta, datetime
def ceil_date(date, **kwargs):
secs = timedelta(**kwargs).total_seconds()
return datetime.fromtimestamp(date.timestamp() + secs - date.timestamp() % secs)
def floor_date(date, **kwargs):
secs = timedelta(**kwargs).total_seconds()
return datetime.fromtimestamp(date.timestamp() - date.timestamp() % secs)
用法与timedelta相似,因为传递了kwargs
now = datetime.now() #15:12:12
ceil_date(now, minutes=5) #15:15:00
floor_date(now, minutes=5) #15:10:00