2 回答
TA贡献1828条经验 获得超6个赞
from datetime import datetime, timedelta
# get the date and time for now
now = datetime.now()
# get the current day at midnight
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
# get Tuesday at midnight
tues = today + timedelta( (1-today.weekday()) % 7 )
# get the seconds from now until Tuesday at midnight
seconds_to_tues_midnight = (tues - now).total_seconds()
# get the seconds from now until Tuesday at noon
seconds_to_tues_noon = seconds_to_tues_midnight + timedelta(hours=12)/timedelta(seconds=1)
作为函数
from typing import Tuple
def time_to_tuesday(now: datetime) -> Tuple[float, float]:
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
tues = today + timedelta( (1-today.weekday()) % 7 )
midnight = (tues - now).total_seconds()
noon = midnight + timedelta(hours=12)/timedelta(seconds=1)
return midnight, noon
time_to_tuesday(datetime.now())
TA贡献1719条经验 获得超6个赞
第一个问题
我想获得未来星期二中午 12:00 之前的准确时间(以秒为单位)
我想您想要从今天开始直到星期二 12:00 的准确时间(以秒为单位)
import datetime
def relative_date(reference, weekday, timevalue):
hour, minute = divmod(timevalue, 1)
minute *= 60
days = reference.weekday()+(reference.weekday() - weekday)
return (reference + datetime.timedelta(days=days)).replace(hour=int(hour), minute=int(minute), second=0, microsecond=0)
today = datetime.datetime.now()
Tuesday = relative_date(today, 1, 12)
seconds_to_call = (Tuesday - today).total_seconds()
print(seconds_to_call)
# OUTPUT: 405778.097769
您必须计算今天和下周二两个日期之间的差异。该函数relative_date计算下周二的确切日期并将小时设置为12:00:00.000。
第二个问题
我想运行程序获取 00:00 之前的秒数,然后获取 12 点之前的秒数 (43,200)
你可以这样做:
import datetime
def relative_date(reference, weekday, timevalue):
hour, minute = divmod(timevalue, 1)
minute *= 60
days = reference.weekday()+(reference.weekday() - weekday)
return (reference + datetime.timedelta(days=days)).replace(hour=int(hour), minute=int(minute), second=0, microsecond=0)
today = datetime.datetime.now()
Tuesday_midnight = relative_date(today, 1, 0)
seconds_to_call = ((Tuesday_midnight - today) + datetime.timedelta(hours=12)).total_seconds()
print(seconds_to_call)
# OUTPUT: 405778.097769
在这种情况下,计算直到午夜的时间是没有用的,您可以直接从中午获取total_seconds,如第一个问题的代码中所示。
添加回答
举报