添加timedelta时,如何在第二天开始使用datetime?

编程入门 行业动态 更新时间:2024-10-26 14:29:08
本文介绍了添加timedelta时,如何在第二天开始使用datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

鉴于当前时间 23:30:00 ,我添加了两个小时(7200秒)。如何获得同一天的时间?所以我想要结果 25:30:00 。

Given a current time of 23:30:00 and I add two hours (7200 seconds). How can I get the time of the same day? So I want as a result 25:30:00.

目前我只能得到第二天:

Currently I am only able to get the time of the next day:

>>> from datetime import datetime, timedelta >>> current_time = "23:30:00" >>> duration = 3600 >>> (datetime.strptime(current_time, "%H:%M:%S") + timedelta(seconds=duration)).strftime("%H:%M:%S") '00:30:00'

推荐答案

如果您只想增加小时数,秒,并创建一个字符串:

If you are just wanting to increment hours minutes, seconds and create a string:

def weird_time(current_time,duration): start = datetime.strptime(current_time, "%H:%M:%S") st_hr, st_min, st_sec = start.hour, start.minute, start.second mn, secs = divmod(duration, 60) hour, mn = divmod(mn, 60) mn, secs = st_min+mn, st_sec+secs if secs > 59: m, secs = divmod(secs,60) mn += m if mn > 59: h, mn = divmod(mn,60) hour += h return "{:02}:{:02}:{:02}".format(st_hr+hour, mn, secs)

输出:

In [19]: weird_time("23:30:00",7200) Out[19]: '25:30:00' In [20]: weird_time("23:30:00",3600) Out[20]: '24:30:00' In [21]: weird_time("23:30:59",7203) Out[21]: '25:31:02' In [22]: weird_time("23:30:59",3601) Out[22]: '24:31:00'

自己计算,我们也可以使用timedelta计算总秒数,并从中进行计算:

Instead of doing all the calculations ourselves we can also use timedelta to calculate the total seconds and do our calculations from that:

from datetime import datetime,timedelta def weird_time(current_time,duration): start = datetime.strptime(current_time, "%H:%M:%S") st_hr, st_min, st_sec = start.hour, start.minute, start.second comb = timedelta(minutes=st_min,seconds=st_sec) + timedelta(seconds=duration) mn, sec = divmod(comb.total_seconds(), 60) hour, mn = divmod(mn, 60) return "{:02}:{:02}:{:02}".format(int(st_hr+hour), int(mn), int(sec))

哪个输出相同:

In [29]: weird_time("23:30:00",7200) Out[29]: '25:30:00' In [30]: weird_time("23:30:00",3600) Out[30]: '24:30:00' In [31]: weird_time("23:30:59",7203) Out[31]: '25:31:02' In [32]: weird_time("23:30:59",3601) Out[32]: '24:31:00' In [33]: weird_time("05:00:00",3600) Out[33]: '06:00:00'

小时只需要增加,我们需要抓住的部分是当任一秒,分钟或两者的总和大于59时。

The hours just need to be incremented, the part that we need to catch is when either the combined total of either seconds, minutes or both is greater than 59.

更多推荐

添加timedelta时,如何在第二天开始使用datetime?

本文发布于:2023-11-24 02:56:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623719.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第二天   如何在   timedelta   datetime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!