一篇文章看懂python时间模块的使用

469次阅读
没有评论

一篇文章看懂python时间模块的使用

在开发中经常会与时间打交道,如:获取事件戳,时间戳的格式化等,这里简要记录一下python操作时间的方法。

python中常见的处理时间的模块:

time:处理时间的模块,如获取时间戳,格式化日期等

datetime:date和time的结合体,处理日期和时间

calendar:日历相关的模块,如:处理年历/月历

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)

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:时间戳。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-01发表,共计2278字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)