首页 > 解决方案 > dt.datetime 减去两个日期得到之间的时间我如何摆脱或美化秒和毫秒

问题描述

下面的代码只是从万圣节和圣诞节中减去今天的日期,以获得天、小时、分钟和秒的差异,我想去掉毫秒。最好的方法是什么。我了解使用 f 字符串格式化日期,但不知道如何摆脱毫秒结果

import datetime as dt


halloween_date = dt.datetime(2020, 10, 31)
xmas_date = dt.datetime(2020, 12, 25)
today_date = dt.datetime.today()
time_between_halloween = today_date - halloween_date
time_between_xmas = today_date - xmas_date
print(f"""it is {time_between_halloween} until Halloween and \
{time_between_xmas} until christmas""")

他的结果包括一个看起来像 -74 天的答案,16:32:36.458040 我想摆脱毫秒?更新:我能够从下面发布的代码中得到我想要的东西,似乎应该有一种更雄辩的方式来获得相同的结果,可能使用导入的模块。

import datetime as dt


halloween_date = dt.datetime(2020, 10, 31)
xmas_date = dt.datetime(2020, 12, 25)
today_date = dt.datetime.today()
time_between_halloween = halloween_date - today_date
time_between_xmas = xmas_date - today_date
xmas_total_seconds = time_between_xmas.total_seconds()
xmas_total_minutes = xmas_total_seconds // 60
xmas_seconds = abs(xmas_total_seconds)
xmas_days = time_between_xmas.days
xmas_hours1 = xmas_seconds // 3600
xmas_hours = xmas_hours1 - (xmas_days * 24)
xmas_total_hour = (xmas_days * 24) + xmas_hours
xmas_minutes1 = xmas_seconds // 60
xmas_minutes = xmas_minutes1 - (xmas_total_hour * 60)
print(f"""Xmas is {xmas_days} days, {xmas_hours:.0f} hours and \
{xmas_minutes:.0f} minutes away.""")
hallo_total_seconds = time_between_halloween.total_seconds()
hallo_total_minutes = hallo_total_seconds // 60
hallo_seconds = abs(hallo_total_seconds)
hallo_days = time_between_halloween.days
hallo_hours1 = hallo_seconds // 3600
hallo_hours = hallo_hours1 - (hallo_days * 24)
hallo_total_hour = (hallo_days * 24) + hallo_hours
hallo_minutes1 = hallo_seconds // 60
hallo_minutes = hallo_minutes1 - (hallo_total_hour * 60)
print(f"""Halloween is {hallo_days} days, {hallo_hours:.0f} hours and \
{hallo_minutes:.0f} minutes away.""")

我当前时间 10:27 EST 8/19 的输出如下:圣诞节是 127 天 13 小时 32 分钟。距离万圣节还有 72 天 13 小时 32 分钟。

我确实看到我可以制作 time_between_halloween 和 time_between_xmas =abs(xxx) 并且会删掉几行,但它仍然看起来很啰嗦..

标签: pythonpython-3.x

解决方案


datetime.timedelta对象以三个时间增量保存它们的数据:天、秒、微秒。

time_between_xmas.days对象能够使用OR等属性在本机公开任何 OR 所有这三个值time_between_xmas.microseconds

一种方法是创建一个timedelta具有相同微秒数的第二个对象,并从您的对象中减去该微秒数:

import datetime as dt

halloween_date = dt.datetime(2020, 10, 31)
xmas_date = dt.datetime(2020, 12, 25)
today_date = dt.datetime.today()
time_between_halloween = today_date - halloween_date
time_between_xmas = today_date - xmas_date


# Each of the following lines sets the number of microseconds
#     in the second date time object to be able to remove
#     that number of microseconds from your timedelta objects.
time_between_xmas = time_between_xmas - dt.timedelta(microseconds=time_between_xmas.microseconds)
time_between_halloween = time_between_halloween - dt.timedelta(microseconds=time_between_halloween.microseconds) 

print(f"""it is {time_between_halloween} until Halloween and \
{time_between_xmas} until christmas""")

 

推荐阅读