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

Python时间和日期函数,轻松处理时间数据

发布时间:2023-06-13 04:30:04

Python的时间和日期函数是处理日期、时间和时间戳的标准工具。它们提供了许多功能,可以轻松处理时间数据。本文将介绍Python中常用的时间和日期函数,以及如何使用它们。

1. time模块

time模块提供了处理时间的基本函数。其中最常用的是time()函数,它返回当前时间的时间戳。例如:

import time

current_time = time.time()
print(current_time)

输出结果为:

1591004223.2723148

时间戳是从1970年1月1日00:00:00 UTC到当前时间的秒数。在Python中,可以使用time()函数将时间戳转换为结构化时间。

import time

current_time = time.time()
time_struct = time.gmtime(current_time)
print(time_struct)

输出结果为:

time.struct_time(tm_year=2020, tm_mon=6, tm_mday=1, tm_hour=8, tm_min=5, tm_sec=47, tm_wday=0, tm_yday=153, tm_isdst=0)

time.struct_time是一个元组,包含年、月、日、小时、分钟、秒、星期、一年中的第几天和是否为夏令时等信息。

2. datetime模块

datetime模块是Python处理日期和时间的重要工具。它提供了许多函数,可以轻松处理日期和时间。

现在我们将datetime模块的datetime()函数用于创建一个新的datetime对象。

import datetime

current_time = datetime.datetime.now()
print(current_time)

输出结果为:

2020-06-01 09:16:11.875074

我们可以使用strftime()函数将datetime对象格式化为字符串。

import datetime

current_time = datetime.datetime.now()
formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_time)

输出结果为:

2020-06-01 09:19:51

strftime()函数接受一个格式化字符串作为参数,并将datetime对象格式化为指定格式的字符串。

我们也可以使用strptime()函数将字符串转换为datetime对象。

import datetime

time_str = '2020-06-01 09:25:39'
time_obj = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print(time_obj)

输出结果为:

2020-06-01 09:25:39

strptime()函数接受两个参数:一个是要转换的字符串,另一个是格式化字符串。

3. timedelta对象

timedelta对象表示两个日期或时间之间的差异。它可以在datetime对象上进行算术运算。

import datetime

date1 = datetime.datetime.strptime('2020-05-31', '%Y-%m-%d')
date2 = datetime.datetime.strptime('2020-06-01', '%Y-%m-%d')
diff = date2 - date1
print(diff.days)

输出结果为:

1

我们可以使用timedelta()函数创建timedelta对象并执行算术操作。

import datetime

td1 = datetime.timedelta(days=1)
td2 = datetime.timedelta(seconds=100)
td3 = datetime.timedelta(weeks=2)

time1 = datetime.datetime.now()
time2 = time1 + td1
time3 = time1 - td2
time4 = time1 + td3

print(time1)
print(time2)
print(time3)
print(time4)

输出结果为:

2020-06-01 09:45:51.559329
2020-06-02 09:45:51.559329
2020-06-01 09:44:11.559329
2020-06-15 09:45:51.559329

4. calendar模块

calendar模块提供了许多函数,可以帮助我们处理日历和日期。例如,我们可以使用calendar.monthrange()函数获取指定月份的天数和该月份的 天是星期几。

import calendar

month_range = calendar.monthrange(2020, 6)
print(month_range)

输出结果为:

(0, 30)

返回值是一个元组, 个元素是指定月份的 天是星期几(0代表星期一,1代表星期二),第二个元素是指定月份的天数。

我们还可以使用calendar.isleap()函数判断指定年份是否为闰年。

import calendar

is_leap = calendar.isleap(2020)
print(is_leap)

输出结果为:

True

5. pytz模块

pytz模块提供了两个主要的类来处理时区:tzinfo和timezone。它可以帮助我们在不同的时区中处理时间数据。

import datetime
import pytz

tz_losangeles = pytz.timezone('America/Los_Angeles')
tz_berlin = pytz.timezone('Europe/Berlin')

time1 = datetime.datetime.now(tz_losangeles)
time2 = datetime.datetime.now(tz_berlin)

print(time1)
print(time2)

输出结果为:

2020-05-31 22:45:51.872225-07:00
2020-06-01 07:45:51.872225+02:00

我们创建了两个不同的时区对象,并使用它们来获取当前时间。输出结果显示,这两个时间之间相差9小时。

这就是Python中的时间和日期函数。它们可以轻松处理时间数据,对于需要处理时间的任何应用程序都很重要。