Python时间处理实战:time、datetime与calendar模块详解

Cora
Cora
发布时间:2026-10-13 | 3人浏览过
原创

本文详细介绍Python中处理时间的三大核心模块:time、datetime和calendar。涵盖时间戳与字符串互转、当前时间获取、整分钟/小时计算、日期差值运算及月历打印等常用功能,提供具体代码示例与封装方法,帮助开发者高效处理时间相关逻辑。

Python时间处理概述

前言:

在软件开发过程中,时间处理是常见需求,例如获取事件戳、进行时间戳格式化等操作。本文简要梳理Python中处理时间的相关方法。

Python中常用的时间处理模块包括:

  • time:专门用于处理时间的模块,支持获取时间戳、格式化日期等功能。
  • datetime:结合date和time功能的模块,用于处理日期和时间。
  • calendar:与日历相关的模块,可用于处理年历或月历。

time模块详解

time模块介绍

说明:time模块主要讲解如下内容:

1.时间戳 --> 时间元组格式(time.struct_time) --> 日期字符串

2.日期字符串 --> 时间元组格式(time.struct_time) --> 时间戳

3.获取当前时间的分钟/秒

4.获取整分钟/整小时时间戳

1.时间戳 --> 时间元组格式(time.struct_time) --> 日期字符串

时间戳 --> 时间元组格式

time.localtime(timestamp) # 参数timestamp为秒级时间戳

例子:


import time

time_tuple = time.localtime(time.time())
print time_tuple # time.struct_time(tm_year=2019, tm_mon=1, tm_mday=30, tm_hour=11, tm_min=29, tm_sec=33, tm_wday=2, tm_yday=30, tm_isdst=0)

时间元组 --> 日期字符串

time.strftime(format, p_tuple=None):format:格式化的日期样式;p_tuple:时间元组

例子:


time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print time_format # 2019-01-30 11:48:07

封装成方法:


def timestamp_format(timestamp):
 """
 :brief 时间戳格式化
 :param timestamp: 时间戳
 :return: 格式化后的日期
 """
 return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))

2.日期字符串 --> 时间元组格式(time.struct_time) --> 时间戳

日期字符串 --> 时间元组

time.strptime(string, format) # string:日期字符串,format:该日期字符串对应的格式化格式

例子:


import time

time_str_to_tuple = time.strptime("2019-01-30 11:48:07", "%Y-%m-%d %H:%M:%S")
print time_str_to_tuple # time.struct_time(tm_year=2019, tm_mon=1, tm_mday=30, tm_hour=11, tm_min=48, tm_sec=7, tm_wday=2, tm_yday=30, tm_isdst=-1)

时间元组 --> 时间戳

time.mktime(p_tuple):p_tuple:时间元组

例子:


time_tuple_to_timestamp = int(time.mktime(time_str_to_tuple))
print time_tuple_to_timestamp # 结果:1548820087

封装成方法


def time_str_to_timestamp(date_str, format):
 """
 :brief 将字符串日期转换为时间戳
 :param date_str: 日期字符串,如:2019-01-30 11:48:07
 :param format: 日期字符串对应的格式化格式,如:%Y-%m-%d %H:%M:%S
 :return: 时间戳
 """
 return int(time.mktime(time.strptime(date_str, format)))

3.获取当前时间的分钟/秒

获取当前时间戳


timestamp = int(time.time())

获取当前时间的秒


seconds = timestamp % 60
print "seconds:{}".format(seconds)

获取当前时间的分钟


minute = (timestamp - seconds) % (60 * 60)
print "minute:{}".format(minute / 60)

4.获取整分钟/整小时时间戳

思路:

先除以对应的进制值取整,得到舍弃余数部分的整数,然后再乘以对应的进制值


one_minute = 60 # 一分钟
one_hour = one_minute * 60 # 一小时

whole_minute = int(timestamp / one_minute) * one_minute
whole_hour = int(timestamp / one_hour) * one_hour

datetime模块详解

datetime模块介绍

datetime模块中常见的类:

  • datetime.date:处理日期
  • datetime.time:处理时间
  • datetime.datetime:处理日期和时间
  • datetime.timedelta:处理时间差

说明:datetime模块主要讲解如下内容

1.时间戳 --> datetime时间格式 --> 日期字符串

2.日期字符串 --> datetime时间格式 --> 时间元组格式(time.struct_time) --> 时间戳

3.时间差的使用,根据当前时间获取前N天的时间

1.时间戳 --> datetime时间格式 --> 日期字符串

时间戳 --> datetime时间格式

datetime.datetime.fromtimestamp(timestamp) 参数timestamp:时间戳

例子:


import time, datetime

datetime_type = datetime.datetime.fromtimestamp(time.time())
print type(datetime_type) # <type 'datetime.datetime'>

datetime时间格式 --> 日期字符串

datetime.datetime.strftime(format) format:日期字符串对应的格式化格式

例子:


datetime_format = datetime_type.strftime("%Y/%m/%d %H:%M:%S")
print datetime_format # 2019/01/30 16:44:01

2.日期字符串 --> datetime时间格式 --> 时间元组格式(time.struct_time) --> 时间戳

日期字符串 --> datetime时间格式

datetime.datetime.strptime(date_str, format) date_str:字符串日期 format:日期字符串对应的格式化格式

例子:


datetime_type = datetime.datetime.strptime('2019/01/30 16:44:01', '%Y/%m/%d %H:%M:%S')
print type(datetime_type) # <type 'datetime.datetime'>
# print datetime_type.timestamp()
print time.mktime(datetime_type.timetuple())

datetime时间格式 --> 时间元组格式(time.struct_time) --> 时间戳

datetime.datetime.timetuple(): datetime转换为时间元组

例子:


datetime_type_to_timestamp = int(time.mktime(datetime_type.timetuple()))
print datetime_type_to_timestamp

3.时间差的使用,根据当前时间获取前N天的时间

datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)

参数说明:

1.days:天

2.seconds:秒

3.microseconds:毫秒 1秒 = 10^3 毫秒

4.milliseconds:微秒 1秒 = 10^6 微秒

5.minutes,分钟

6.hours:小时

7.weeks:星期 1weeks = 7days

例子:


day_timedelta = datetime.timedelta(days=1) # 获取1天的时间值
forward_datetime = datetime.datetime.today() - day_timedelta # 获取前一天的datetime值
print forward_datetime

calendar模块详解

calendar模块介绍

说明:

这里介绍一下使用month(year, month)方法打印出某年某月下的月历时间

例子:


import calendar
cal = calendar.month(2019, 1) # 打印出2019年1月的月历
print cal

喜欢点个赞!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表