dt.datetime减去两个日期得到如何消除或美化秒和毫秒之间的时间

2024-06-10 14:00:17 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码只是从万圣节和圣诞节中减去今天的日期,得到日、小时、分和秒的差值,我想去掉毫秒。最好的方法是什么。我理解用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.""")

我目前在美国东部标准时间8月19日10:27时的输出如下: 离圣诞节还有127天13小时32分钟。 离万圣节还有72天13小时32分钟

我确实看到我可以在万圣节和圣诞节之间留出时间,这样可以省去几行,但这似乎还是有点冗长


Tags: todaydatetimedatetimedtbetweendaystotal
1条回答
网友
1楼 · 发布于 2024-06-10 14:00:17

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

对象能够使用time_between_xmas.daystime_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""")

 

相关问题 更多 >