用 Python 将时间转换为小时、分钟和秒钟

不要担心,这不是一个无聊的历史教程,相反,我们将寻找不同的方法来转换 时间在秒钟时间在小时,分钟和秒钟

向前移动,我们将以小时,分钟和秒钟表示时间,以优选格式的 **时间。

它将看起来像:

12:46:40

毫无疑问,python有惊人的模块来为我们进行转换,但让我们先尝试写自己的程序,然后再转到内置模块。

建立自定义函数,将时间转换为小时分钟和秒

要写出自己的转换函数,我们首先需要在数学上思考问题。

** 如何将秒转换为偏好格式?**

您需要获得 **小时、分钟和秒的值。

我们将假设,秒数中的时间不超过一天的总秒数;如果这样做,我们将把它分成一天的总秒数,然后取其余数。

这在数学上表示为:

1seconds = seconds % (24 * 3600)

**%**操作员提供剩余的。

24*3600因为一个小时有3600秒(60*60)**和一天有24小时。

在此之后,我们可以继续从秒计算小时值。

1 获取小时值

要从秒数中获取小时值,我们将使用 **地板分区运算符(//)。

它返回量子中的 ** 完整部分**。

由于我们需要时数,我们将秒数(n)的总数分为一个小时中的秒数 **(3600)。

从数学上来说,这就是:

1hour = seconds // 3600

在此之后,我们需要 **计算分钟。

2. ** 获取分钟值**

要计算分钟的值,我们需要先将秒数分为3600,然后拿出剩余的数。

从数学上来说,这就是:

1seconds = seconds % 3600

现在从上述结果计算分钟的值,我们将再次使用地板操作器。

1minutes = seconds // 60

一分钟有60秒,所以我们将秒数的值降低为60秒。

计算分钟值后,我们可以继续计算 **我们偏好格式的秒值。

3. ** 获取秒数值**

要获取秒数值,我们需要将秒数的总数分为一分钟中的秒数 (60),然后取剩余数。

数学上这样做是如下:

1seconds = seconds % 60

这将为我们所喜爱的格式提供我们需要的第二个值。

四、完整代码

让我们把上述知识汇编成一个Python函数。

 1def convert_to_preferred_format(sec):
 2   sec = sec % (24 * 3600)
 3   hour = sec // 3600
 4   sec %= 3600
 5   min = sec // 60
 6   sec %= 60
 7   print("seconds value in hours:",hour)
 8   print("seconds value in minutes:",min)
 9   return "%02d:%02d:%02d" % (hour, min, sec) 
10
11n = 10000
12print("Time in preferred format :-",convert(n))

出发点:**

1seconds value in hours: 2
2seconds value in minutes: 46
3Time in preferred format :- 02:46:40

使用时间模块

现在让我们看看一个内置的模块,允许我们在一个代码行中将秒转换为我们偏好的格式。

时间模块在Unix系统(系统依赖)中定义时代为 1970年1月1日,00:00:00 (UTC)。时代基本上是计算机时间的开始。

要在您的系统中输出时代,请使用以下代码行:

1time.gmtime(0)

Time Epoch

要将秒转换为偏好格式,请使用以下代码行:

1time.strftime("%H:%M:%S", time.gmtime(n))

此行以n,然后允许您单独输出小时、分钟和秒值。

Python 的完整代码如下:

1import time
2n=10000
3time_format = time.strftime("%H:%M:%S", time.gmtime(n))
4print("Time in preferred format :-",time_format)

出发点:**

1Time in preferred format :- 02:46:40

时间模块还为您提供显示某些额外信息的选项,如日期、月期和年份。

%adisplay abbreviated weekday name.
%Adisplay full weekday name.
%bdisplay abbreviated month name.
%Bdisplay full month name.
%cdisplay the appropriate date and time representation.
%ddisplay day of the month as a decimal number [01,31].

让我们尝试使用 %a%b

1import time
2n=100000000000
3time_format = time.strftime("Day: %a, Time: %H:%M:%S, Month: %b", time.gmtime(n))
4print("Time in preferred format :-",time_format)

出发点:**

1Time in preferred format :- Day: Wed, Time: 09:46:40, Month: Nov

使用日期模块

您还可以使用 timedelta 方法在 **DateTime 模块**中将秒转换为您喜欢的格式。

它将时间显示为从该时代过去的日子,小时,分钟和秒钟。

Python 代码将秒转换为使用 Datetime 模块的偏好格式如下:

1import datetime
2n= 10000000
3time_format = str(datetime.timedelta(seconds = n))
4print("Time in preferred format :-",time_format)

出发点:**

1Time in preferred format :- 115 days, 17:46:40

结论

本教程看了三种不同的方法,你可以用来将秒转换为小时,分钟和秒。

您要么写自己的函数,要么使用内置模块,我们开始写自己的函数,然后看看 timeDateTime模块。

Published At
Categories with 技术
Tagged with
comments powered by Disqus