python - 如何将一组数字更改为时间 [Python]

标签 python time

编程新手,所以任何帮助都是很好的帮助,哈哈。所以我的问题是我是否接受一个号码前。 738218(任何数字都可以)我怎样才能将其转换为小时,分钟,秒(例如19小时,36分钟,26秒)。我尝试了一些我发现的例子,但我不断收到错误。这就是我现在所拥有的。

from datetime import timedelta
import time
sec = input('Enter a number to covert to a formal timestap: ')
hours = sec/12 `enter code here`
minutes = sec/60
time.strftime('%H:%M:%S', time.gmtime(sec))
print(time.strtime)

最佳答案

欢迎来到 StackOverflow!我更新了您的脚本并添加了一些注释:

seconds = int(input('Enter a number to convert to a formal timestamp: '))
hours = seconds // 3600  # there are 3600 seconds per hour
seconds -= hours * 3600  # don't double count seconds counted by hours
minutes = seconds // 60  # there are 60 seconds per minute
seconds -= minutes * 60  # don't double count seconds counted by minutes
time_string = "{}:{}:{}".format(hours, minutes, seconds)
print(time_string)

单独浏览一些行:

seconds = int(input('Enter a number to convert to a formal timestamp: '))

我假设您正在使用 Python 3。如果是这样,input 正是我们想要的。然而,如果您使用的是 Python 2,input 会做一些稍微相关的事情,而我们真正想要的是其他东西 - raw_input。当从 2 移动到 3 时,raw_input 被重命名为 input。无论哪种方式,我们都会将用户输入的任何内容传递给 int 函数并将其转换为整数值。

time_string = "{}:{}:{}".format(hours, minutes, seconds)

"{}:{}:{}" 是格式字符串。您可以阅读有关它们的更多信息 in the Python docs 。每一对大括号都是传递给 format 方法的参数的占位符;第一个括号被第一个参数小时替换,第二对括号被第二个参数分钟替换,依此类推。

如果您使用的是 Python 2,代码将无法完全按照指定方式工作。幸运的是,它们中的大多数都可以通过从 __future__ 模块导入来向后移植到 Python 2;在这种情况下,唯一的手动更改是将 input 切换为 raw_input。这是 Python 2 中的相同代码:

from __future__ import print_function, division

seconds = int(raw_input('Enter a number to convert to a formal timestamp: '))
hours = seconds // 3600  # there are 3600 seconds per hour
seconds -= hours * 3600  # don't double count seconds counted by hours
minutes = seconds // 60  # there are 60 seconds per minute
seconds -= minutes * 60  # don't double count seconds counted by minutes
time_string = "{}:{}:{}".format(hours, minutes, seconds)
print(time_string)

关于python - 如何将一组数字更改为时间 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32534752/

相关文章:

python - 蒙特卡洛疯狂三月模拟

r - as_datetime() 错误 : All formats failed to parse

javascript - 如果事件没有发生jquery/javascript,如何记录 react 时间?

java - 在java中查找EDT时间

ios - iOS 上的 DST 独立时间

MySQL - 有条件的操作

python - 有人可以告诉我为什么这段代码没有按预期工作吗?

python - 如何有效地将新行附加到大文件的开头?

python - 如何获取我之前使用其类找到的图像的 xpath?

python - 符号翻转傅立叶变换 Python Numpy Array