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

Python中的datetime模块及其函数的使用

发布时间:2023-06-08 15:44:32

Python中的datetime模块是用于处理日期和时间相关操作的模块,它提供了日期、时间、时间间隔等数据类型以及各种日期时间操作函数。对于需要处理时间日期数据的Python程序,datetime模块是十分重要的工具。

1. datetime模块中的类

1.1 datetime

datetime是最基本的日期时间类型,它包含年、月、日、时、分、秒和微秒等信息。

datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

其中,year、month和day是必需参数,其它参数可选。它们的类型都是int。

1.2 timedelta

timedelta表示时间间隔,常用于日期时间的计算。

timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

其中,参数都是可选的,并且都是int类型。

1.3 date

date表示日期,它包含年、月、日信息。

date(year, month, day)

其中,year、month和day是必需参数,它们的类型都是int。

1.4 time

time表示时间,它包含时、分、秒和微秒信息。

time([hour[, minute[, second[, microsecond[,tzinfo]]]]])

其中,参数都是可选的,并且都是int类型。

1.5 tzinfo

tzinfo表示时区信息,用于处理跨时区问题。它是一个抽象基类,不能直接实例化,需要自己实现。

tzinfo是一个抽象基类,在datetime中有一个子类timezone,可以用它提供的时区信息,创建datetime对象。

2. datetime模块中的常用函数

2.1 datetime.now()

该函数返回当前本地日期时间。它不需要任何参数。

示例代码:

import datetime

now = datetime.datetime.now()

print("当前日期时间为:",now)

输出结果:

当前日期时间为: 2022-01-20 14:28:14.882135

2.2 datetime.date()

该函数返回指定日期所对应的date对象。

示例代码:

import datetime

d = datetime.date(2022,1,20)

print("指定日期为:",d)

输出结果:

指定日期为: 2022-01-20

2.3 datetime.time()

该函数返回指定时间所对应的time对象。

示例代码:

import datetime

t = datetime.time(14,30,0)

print("指定时间为:",t)

输出结果:

指定时间为: 14:30:00

2.4 datetime.datetime.strptime()

该函数将一个字符串按照指定的格式转换为datetime对象。

datetime.datetime.strptime(date_string, format)

其中,date_string表示要转换的字符串,format表示字符串的格式。

示例代码:

import datetime

date_str = '2022-01-20 14:30:00'

dt = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')

print("转换后的日期时间为:",dt)

输出结果:

转换后的日期时间为: 2022-01-20 14:30:00

2.5 datetime.datetime.strftime()

该函数将一个datetime对象按照指定的格式输出字符串。

datetime.datetime.strftime(date_string, format)

其中,date_string表示要转换的datetime对象,format表示输出字符串的格式。

示例代码:

import datetime

today = datetime.datetime.now()

s = today.strftime("%Y-%m-%d %H:%M:%S")

print("转换后的字符串为:",s)

输出结果:

转换后的字符串为: 2022-01-20 14:28:14

3. 结语

datetime模块为我们提供了便捷的日期和时间操作功能,我们可以通过这些函数,轻松地处理各种日期和时间相关的计算。这样便于我们更好地完成各类时间日期任务。