给定日期还剩多少时间(天,小时,分钟,秒) [英] How much time left to given date (days, hours, mins, s.)

查看:81
本文介绍了给定日期还剩多少时间(天,小时,分钟,秒)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中创建某种截止日期时钟".关于时差计算有很多主题,我遵循了一些主题并将它们组合在一起:

I'm trying to make some kind of "deadline clock" in python. There is lot of topics about time difference calculations and I followed some and put together this kind of code:

import datetime
from dateutil.relativedelta import relativedelta

# Get current time:
today = datetime.date.today()
timenow = datetime.datetime.now()
current_time = str(today) + " " + str(timenow.strftime("%H:%M:%S"))

# Set deadline:
deadline = "2019-12-12 15:00:00"

# Calculate difference:
start = datetime.datetime.strptime(current_time,'%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')
diff = relativedelta(ends, start)

print("Now: " + current_time)
print("Deadline: " + deadline)

print(str(diff.days) + " days. " 
      + str(diff.hours) + " hours. " 
      + str(diff.minutes) + " minutes. " 
      + str(diff.seconds) + " seconds. " 
      )

但是问题是,它将始终显示最多一个月的差额...那么问题出在哪里?

But the problem is, that it will allways show just maximum of one month difference... So where is the problem?

推荐答案

只需将开始日期减去结束日期即可.

Just substract your start date with the end date.

import datetime
today = datetime.date.today()
timenow = datetime.datetime.now()
deadline = "2019-12-12 15:00:00"
current_time = str(today) + " " + str(timenow.strftime("%H:%M:%S"))
start = datetime.datetime.strptime(current_time,'%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')

print(start - ends)

如评论中所建议,您实际上并不需要分别使用 .now() .now())返回当前日期和时间作为datetime对象本身.

As suggested in the comments, you don't really need to to use both .today() and .now() separately, .now() returns the current date and time as a datetime object itself.

import datetime
timenow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
deadline = "2019-12-12 00:00:00"
start = datetime.datetime.strptime(timenow,'%Y-%m-%d %H:%M:%S')
ends = datetime.datetime.strptime(deadline, '%Y-%m-%d %H:%M:%S')
print(start - ends)

这篇关于给定日期还剩多少时间(天,小时,分钟,秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆