为了账号安全,请及时绑定邮箱和手机立即绑定

如何计算从现在开始加上n天的总秒数

如何计算从现在开始加上n天的总秒数

largeQ 2023-09-26 14:31:45
我想在每周二中午 12:00 发送通知我想获得未来星期二中午 12:00 之前的准确时间(以秒为单位)import datetimefrom datetime import date , timedeltatoday = datetime.date.today()Tuesday = datetime.timedelta( (1-today.weekday()) % 7 ) + timedelta(hours=12)seconds_to_call = Tuesday.total_seconds() print(seconds_to_call)# Gives exactly 5 days in seconds 432,000 + timedelta(hours=12) 43200# 以秒为单位给出 5 天 432,000 + timedelta(hours=12) 43200我如何获得星期二 00:00 加上 12 小时 timedelta(hours=12) 43200那么我周二中午 12 点
查看完整描述

2 回答

?
30秒到达战场

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())


查看完整回答
反对 回复 2023-09-26
?
慕侠2389804

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,如第一个问题的代码中所示。


查看完整回答
反对 回复 2023-09-26
  • 2 回答
  • 0 关注
  • 114 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信