时间和日期函数(time、datetime等)
时间和日期函数是编程中经常使用的函数,它们可以用来获取当前时间和日期,在不同时间格式之间进行转换等。Python 语言中常见的时间和日期函数包括 time、datetime、date、calendar 等。
一、time 模块
time 模块提供了获取当前时间、等待一段时间、睡眠等功能。常用的函数包括 time、sleep、asctime、ctime、gmtime 和 localtime。
1. time 函数
time() 函数返回当前时间戳,以秒为单位。时间戳是指从 1970 年 1 月 1 日 00:00:00 开始到现在的秒数。
2. sleep 函数
sleep() 函数可以让程序休眠一定的时间。
3. asctime 函数
asctime() 函数返回当前时间的字符串表示,格式为 “Sun May 19 14:25:58 2019”。
4. ctime 函数
ctime() 函数将一个时间戳转换为字符串表示,格式为 “Sun May 19 14:25:58 2019”。
5. gmtime 函数
gmtime() 函数将一个时间戳转换为一个 UTC 时间的 struct_time 对象。
6. localtime 函数
localtime() 函数将一个时间戳转换为一个本地时间的 struct_time 对象。
二、datetime 模块
datetime 模块提供了处理日期和时间的类和函数。常用的类包括 datetime、date 和 time。
1. datetime 类
datetime 类是 date 和 time 类的组合。它包含了日期和时间的信息,而且提供了一系列对日期和时间进行处理的方法。获取当前时间的方法有 datetime.now()、datetime.utcnow() 和 datetime.fromtimestamp()。
2. date 类
date 类只存储日期信息,而不存储时间信息。它包括年、月、日等属性,提供了一系列用于处理日期的方法。获取当前日期的方法有 date.today()、date.fromtimestamp() 和 datetime.date()。
3. time 类
time 类只存储时间信息,而不存储日期信息。它包括时、分、秒等属性,提供了一系列用于处理时间的方法。获取当前时间的方法有 datetime.time()。
三、calendar 模块
calendar 模块提供了一些有关日历的函数和类。常用的函数包括 month、monthrange、weekday 和 weekheader。
1. month 函数
month() 函数用于输出一个月的日历。它的参数包括年和月。
2. monthrange 函数
monthrange() 函数用于获取一个月的日历范围。它的参数包括年和月。
3. weekday 函数
weekday() 函数用于获取某一天是星期几。它的参数包括年、月和日。
4. weekheader 函数
weekheader() 函数用于获取星期的名称。它的参数为可选参数 n,默认为 3。
总结:
今天我们学习了 Python 中常用的时间和日期函数,包括 time、datetime、date、calendar 等模块。这些模块提供了获取当前时间和日期,等待一段时间,睡眠等功能,非常方便。同时,我们学习了常见的函数和类,如 time、sleep、datetime、date、calendar、gmtime、localtime、month、monthrange、weekday 和 weekheader 等,可以根据不同的需求进行选择和使用。如果你经常需要处理时间和日期,掌握这些函数将对你的工作有很大帮助。
