0
点赞
收藏
分享

微信扫一扫

【Python】一文了解Time模块、Datatime模块、Calendar模块。

b91bff6ffdb5 2023-04-26 阅读 71

目录

前言 

详细介绍

time模块

datatime模块

calendar模块 


前言 

        在 Python 的时间处理中,一般可以使用以下三件套来处理时、分、秒、日期、时间戳等时间相关的操作:

  1. time 模块:提供了基于 C 标准库的时间处理函数,包括时间的获取与转换、程序计时等功能。
  2. datetime 模块:提供了对时间日期的各种操作功能,包括时间格式化、时区切换等。
  3. calendar 模块:提供了一些与日历相关的函数,比如获取月份的日历、某年是否为闰年等。

        time模块是Python标准库中最基础、最常用的模块之一。它提供了各种处理时间的方法和函数,如获取当前时间、格式化时间、计算时间差等。time模块大部分函数的底层实现是 C 语言库的时间处理函数。

        datetime模块是对time模块的补充和扩展,它提供了更加丰富和灵活的时间处理功能,支持更多的时间格式和时间操作,并且功能更加强大。datetime模块提供了日期(date)、时间(time)、日期时间(datetime)等类型的操作。它也是基于C语言的时间库实现的。

        calendar模块提供了一些与日历相关的函数和类。它包含可打印的日历类,可以格式化周和月的天数,并将日历信息转换为不同的格式。基本上,calendar模块提供了一种将日期转换为特定格式的工具。它是纯Python的实现。

详细介绍 

time模块

        time模块是Python中处理时间的基础模块。 time模块提供了实现时间相关操作的函数,例如获取当前时间、延迟执行、获取时间戳等等。 time模块的函数可以分为3类:

a. 获取时间相关函数

b. 格式化时间相关函数

c. 延迟执行相关函数

例如: 

import time
#获取当前时间
now = time.time()
print(now)

#将时间戳转换为可读字符串
time_str = time.ctime(now)
print(time_str)

#获取UTC时间
utc_time_tuple = time.gmtime(now)
print(utc_time_tuple)

#获取本地时间
local_time_tuple = time.localtime(now)
print(local_time_tuple)

#格式化时间
format_time = time.strftime(“%Y-%m-%d %H:%M:%S”, local_time_tuple)
print(format_time)

#将时间字符串解析为时间元组
time_tuple = time.strptime(format_time, “%Y-%m-%d %H:%M:%S”)
print(time_tuple)

#延迟执行
time.sleep(1)

datatime模块

        datetime模块是Python中处理日期和时间的高级模块。 datetime模块是在time模块的基础上开发的,可以提供更精确和高效的时间处理功能。 datetime模块的主要类有3个:

a. date类

        表示一个具体的日期,有3个属性(year、month、day),可以进行日期的加减运算。

b. time类

        表示一天内的时间,有4个属性(hour、minute、second、microsecond),可以进行时间的加减运算。

c. datetime类

        表示一个具体的日期时间,是date类和time类的结合体,具有date类和time类的所有属性和方法。

datetime模块提供了很多函数和方法:

例如:

import datetime

#获取当前时间
current_time = datetime.datetime.now()
print("当前时间:", current_time)

#获取某一天的日期
date = datetime.date(2023, 4, 25)
print("指定日期:", date)

#获取某一时间的时间戳
timestamp = datetime.datetime.timestamp(current_time)
print("当前时间戳:", timestamp)

#获取某一日期的星期几
weekday = date.weekday()
print("星期几:", weekday)

#将字符串转换为日期
string_date = '2023-04-25'
converted_date = datetime.datetime.strptime(string_date, '%Y-%m-%d')
print("转换后的日期:", converted_date)

#将日期转换为字符串
string_date = converted_date.strftime('%Y/%m/%d')
print("转换后的字符串日期:", string_date)

 

calendar模块 

        calendar模块是Python中处理日历相关操作的模块。 calendar模块可以输出各种格式的日历,例如月历、年历等等。calendar模块提供了以下函数:

例如:

import calendar
#输出年历
print(calendar.calendar(2021))

#输出9月份日历
print(calendar.monthcalendar(2021, 9))

#输出指定月的第一天和这一天在一周中的相对位置
print(calendar.monthrange(2021, 9))

#输出指定日期的星期数
print(calendar.weekday(2021, 9, 9))

 

 

举报

相关推荐

0 条评论