Python时间模块
时间:2020-02-23 14:43:36 来源:igfitidea点击:
在本教程中,我们将学习Python时间模块。
我们之前的教程中讨论了Python变量。
当您的工作需要与系统时间同步时,Python时间模块非常有用。
Python时间模块
当您从事实时项目时,可能需要将任务与系统时间同步。
例如,在8点钟时,您的程序应向一群人发送一条消息。
为此,您应该知道如何使用python代码获取系统时间。
为此,您需要导入Python时间模块。
为了获得当前时间,我们需要使用时间模块中的localtime()函数。
该函数从time()函数获取输入。
以下代码将帮助您在python中打印当前时间。
# import the module
import time
# get the current clock ticks from the time() function
seconds = time.time()
currentTime = time.localtime(seconds)
# print the currentTime variable to know about it
print(currentTime,'\n')
# use current time to show current time in formatted string
print('Current System time is :', time.asctime(currentTime))
Python时间格式
我们可以使用strftime函数来格式化时间。
print('Python Time Formatted is :', time.strftime("%d/%m/%Y", currentTime))
产生的输出将如下所示。
Python Time Formatted is : 23/08/2016
日历模块
在上一节中,我们讨论了Python的时间模块。
我们可以使用python时间模块获取当前时间,然后根据需要设置其格式。
在本部分中,我们将使用Python的日历模块来获取有关日历的信息。
以下示例代码将向我们展示日历模块的一些功能。
# import the module
import calendar
# print the current month
print('The month of August is:\n', calendar.month(2016, 8))
# set the first day of the week as sunday
calendar.setfirstweekday(6)
# re print the calender
print('The month of August is:\n', calendar.month(2016, 8))
# print if a year is leap year
print('Is 2016 a leap year? Ans:', calendar.isleap(2016))
print('Is 2015 a leap year? Ans:', calendar.isleap(2015))
以下代码的输出将是
The month of August is:
August 2016
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
The month of August is:
August 2016
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Is 2016 a leap year? Ans: False
Is 2015 a leap year? Ans: True
除了时间和日历,还有其他模块。
例如," datetime"模块," dateutil"模块。

