下面的代码只是从万圣节和圣诞节中减去今天的日期,得到日、小时、分和秒的差值,我想去掉毫秒。最好的方法是什么。我理解用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分钟
我确实看到我可以在万圣节和圣诞节之间留出时间,这样可以省去几行,但这似乎还是有点冗长
datetime.timedelta
对象以三个时间增量保存数据:天、秒、微秒对象能够使用
time_between_xmas.days
或time_between_xmas.microseconds
等属性以本机方式公开这些值中的任何一个或所有三个一种方法是创建第二个具有相同微秒数的
timedelta
对象,并从对象中减去该微秒数:相关问题 更多 >
编程相关推荐