欢迎访问宙启技术站
智能推送

Python时间处理函数及示例

发布时间:2023-06-06 10:40:21

Python中的时间处理是一个非常常用的模块,可以通过时间处理来对时间进行转换、比较、格式化等操作。Python的时间处理模块有很多,常用的有datetime、time、calendar等模块。

一、datetime模块

datetime是Python的一个日期和时间处理模块,常用于日期和时间的计算、格式化和转换等操作。

1. 获取当前时间:

通过datetime模块可以获取当前系统时间,方法如下:

import datetime

now_time = datetime.datetime.now()
print(now_time)

输出示例:

2019-09-25 16:10:06.556017

2. 格式化输出时间:

将获取到的时间按照我们需要的格式进行输出,例如需要将时间输出为:“2019年09月25日 16时10分06秒”,则可以使用strftime()方法进行格式化输出,代码如下:

format_time = now_time.strftime("%Y年%m月%d日 %H时%M分%S秒")
print(format_time)

输出示例:

2019年09月25日 16时10分06秒

3. 时间比较:

在Python中,可以通过比较两个时间的大小判断哪个时间在前、哪个时间在后。例如,比较两个时间,判断哪个更早一些,代码如下:

import datetime

time1 = datetime.datetime(2019, 9, 25, 16, 10, 0)
time2 = datetime.datetime(2019, 9, 24, 16, 0, 0)

if time1 > time2:
    print("时间1比时间2晚")
else:
    print("时间2比时间1早")

输出示例:

时间1比时间2晚

二、time模块

time模块主要用于时间的格式化和转换,常常与datetime模块一起使用。

1. 获取当前时间:

同样地,我们可以使用time模块来获取当前时间,代码如下:

import time

now_time = time.time()
print(now_time)

输出示例:

1569388159.4211845

2. 时间的时间戳表示:

时间戳通常是指从1970年1月1日00:00:00到某一个时间点的所经过的秒数,可以通过time模块的mktime()方法将datetime对象转换为时间戳,代码如下:

import datetime
import time

time1 = datetime.datetime(2019, 9, 25, 16, 10, 0)
timestamp = time.mktime(time1.timetuple())
print(timestamp)

输出示例:

1569388200.0

3. 时间的格式化输出:

和datetime模块类似,time模块也可以将时间进行格式化输出,常用的格式化符号如下:

%Y:年(4位数)
%m:月(取01-12)
%d:日(取01-31)
%H:时(24小时制,取00-23)
%M:分(取00-59)
%S:秒(取00-59)

示例代码如下:

import time

now_time = time.time()
format_time = time.strftime("%Y.%m.%d %H:%M:%S", time.localtime(now_time))
print(format_time)

输出示例:

2019.09.25 16:15:35

三、calendar模块

Python的calendar模块提供了各种日期计算和操作功能,包括年历、月历、判断闰年、获取某个月的天数等功能。

1. 获取某年某月的日历:

使用calendar模块的month()方法,可以获取指定年月的日历,代码如下:

import calendar

cal = calendar.month(2019, 9)
print(cal)

输出示例:

   September 2019
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

2. 判断某一年是否为闰年:

calendar模块中可以使用isleap()方法判断某一年是否为闰年,示例代码如下:

import calendar

year = 2019
is_leap = calendar.isleap(year)
if is_leap:
    print("{0}是闰年".format(year))
else:
    print("{0}不是闰年".format(year))

输出示例:

2019不是闰年

以上是Python中常用的时间处理函数及示例,希望对你有帮助。