【问题标题】:Python how to get current time as an integerPython如何以整数形式获取当前时间
【发布时间】:2020-04-05 09:39:37
【问题描述】:

这是我尝试使用的代码,但它不起作用,因为它是一个字符串

from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
print("time=", current_time)
wake_up=0
x=current_time - wake_up - 0.40
wake_up = float(input("when are you gonna wake up"))
print(x)

我正在尝试制作一个打印当前时间的计算器。 (例如 23:00),然后输入询问您打算什么时候起床并写(例如 08:30),输出应该是“您将获得 09:30 小时和分钟的睡眠”或最好“您将获得 9 小时 30 分钟的睡眠时间”

我试图这样做,但它是一个字符串,无法计算,我试图找到 now.strftime 模块的整数版本。有人可以帮我看看怎么做吗?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您需要使用datetime.strptime(),它接收日期字符串和格式字符串(参考here)并将字符串转换为datetime 对象。

在您的情况下,您将使用以下内容将 wake_up 转换为 datetime 对象:

dt = datetime.strptime(wake_up, "%H:%M")

【讨论】:

    【解决方案2】:

    根据您的代码进行的修改:

    from datetime import datetime, date
    now_time = datetime.now().time()  # get time only
    current_time_str = now.strftime("%H:%M")
    print("time=", current_time_str)
    
    #wake_up = input("when are you gonna wake up")
    wake_up = '08:30'  # assuming this is user input
    wake_up_time = datetime.strptime(wake_up, "%H:%M").time()
    x = datetime.combine(date.today(), wake_up_time) - datetime.combine(date.today(), now_time)
    print(str(x))  #also, you can get hours by x.seconds/3600
    

    其他问题会对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 2017-10-01
      • 2014-04-17
      相关资源
      最近更新 更多