时间模块和时间工具

一、time模块

三种格式
时间戳时间:浮点数 单位为秒
时间戳起始时间:
1970.1.1 0:0:0 英国伦敦时间
1970.1.1 8:0:0 我国(东8区)
结构化时间:元组(struct_time)
格式化时间:str数据类型的

1、常用方法

import time

time.sleep(secs)   推迟指定的时间运行,单位是秒

for i in range(3):
    time.sleep(1)
    print(i)

2、表示时间的三种方式

时间戳(timestamp)、元组(struct_time)、格式化(str_time)的时间字符串

1. 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
我们运行“type(time.time())”,返回的是float类型。
print(time.time())  # 1536050072.5732844(1970年1月1日00:00:00到此刻运行time.time()的时间) 


2. 结构化时间(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一周中第几天,一年中第几天,夏令时)
struct_time = time.localtime()  # 我国的时间
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=16, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)


struct_time = time.gmtime()  # 伦敦的时间
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=8, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)


3. 格式化时间(Format_string):
fmt1 =time.strftime('%H:%M:%S')   # 时分秒(全大写)
fmt2 =time.strftime('%Y-%m-%d')   # 年月日(年可大写可小写,月日小写)
fmt3 =time.strftime('%y-%m-%d')   # 年月日
fmt4 =time.strftime('%c')         # 本地相应的日期表示和时间表示

print(fmt1)  # 16:49:03
print(fmt2)  # 2018-09-04
print(fmt3)  # 18-09-04
print(fmt4)  # Tue Sep  4 16:49:03 2018

3、几种时间格式间的转换

1. 转换

Timestamp ---> struct_time: time.localtime(转成我国的时间)、time.gmtime(转成伦敦时间)
struct_time ---> Timestamp: time.mktime()

Format_string ---> struct_time: time.strptime()
struct_time ---> Format_string: time.strftime()

2. 例子

1. 把格式化时间2018年8月8日转成时间戳时间
str_time = '2018-8-8'
struct_time = time.strptime(str_time,'%Y-%m-%d')
print(struct_time)  # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=220, tm_isdst=-1)
timestamp = time.mktime(struct_time)
print(timestamp)   # 1533657600.0


2. 把时间戳时间转成格式化时间
timestamp = 1500000000
struct_time = time.localtime(timestamp)
str_time = time.strftime('%Y-%m-%d',struct_time)
print(str_time)   # 2017-07-14


3. 写函数,计算本月1号的时间戳时间
通过我拿到的这个时间,能迅速的知道我现在所在时间的年 月
def get_timestamp():
    str_time = time.strftime('%Y-%m-1')
    struct_time = time.strptime(str_time,'%Y-%m-%d')
    timestamp = time.mktime(struct_time)
    return timestamp
ret = get_timestamp()
print(ret)
%y 两位数的年份表示(00-99%Y 四位数的年份表示(0000-9999%m 月份(01-12%d 月内中的一天(0-31%H 24小时制小时数(0-23%I 12小时制小时数(01-12%M 分钟数(00-59%S 秒(00-59%a 本地简化星期名称

%A 本地完整星期名称

%b 本地简化的月份名称

%B 本地完整的月份名称

%c 本地相应的日期表示和时间表示

%j 年内的一天(001-366%p 本地A.M.或P.M.的等价符

%U 一年中的星期数(00-53)星期天为星期的开始

%w 星期(0-6),星期天为星期的开始

%W 一年中的星期数(00-53)星期一为星期的开始

%x 本地相应的日期表示

%X 本地相应的时间表示

%Z 当前时区的名称

%% %号本身
3. python中时间日期格式化符号

二、datetime模块

1、dateime.date

import datetime

1. datetime.date类型(年月日)
注意:datetime.date类型就是time模块的结构化时间,只是它在内部把结构化时间的显示格式化了再打印出来
datetime.date.today()  # 2018-12-21
datetime.date(2018, 12, 21)  # 2018-12-21


2.根据给定的时间戮,返回一个date对象<class 'datetime.date'>
datetime.date.fromtimestamp(timestamp)  # 返回一个date对象,与datetime.date.today()作用相同
datetime.date.fromtimestamp(1528345678)  # 2018-06-07


3.由date日期格式转化为字符串格式
datetime.date.strftime(date对象, format)

datetime.date.strftime(datetime.date(2018,12,20), '%Y-%m-%d')  # 2018-12-20  是 str类型
datetime.date.today().strftime('%Y-%m-%d')  # 2018-12-21
注意:date类型没有strptime

2、datetime.dateime

注意:datetime是继承了date的类
1. datetime.datetime类型(年月日时分秒微妙时区)
datetime.datetime.today()  # 2018-12-21 20:17:50.740914
datetime.datetime.now()  # 2018-12-21 20:17:50.740914

datetime.datetime(2018, 12, 21, 8, 12, 8, 603000)  # 2018-12-21 08:12:08.603000

返回当前日期时间的日期部分
datetime.datetime.today().date()  # 2018-12-21
返回当前日期时间的时间部分
datetime.datetime.now().time()  # 20:19:16.230449


2.根据给定的时间戮,返回一个datetime对象,<class 'datetime.datetime'>
datetime.datetime.fromtimestamp()  # 返回一个datetime对象,与datetime.datetime.today()作用相同
datetime.datetime.fromtimestamp(1528345678)  # 2018-06-07 12:27:58


3. 由日期格式转化为字符串格式
datetime.datetime.strftime(datetime对象, format)

datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')  # 2018-12-21 20:23:14  是str类型
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 2018-12-21 20:23:14


3.由字符串格式转化为日期格式
datetime.datetime.strptime(格式化时间, 时间格式)
datetime.datetime.strptime('2018-12-21 21:01:27', '%Y-%m-%d %H:%M:%S')  # 2018-12-21 21:01:27是datetime对象


4. 结构化时间:元组
注意:这就是结构化时间初始的样子
datetime.datetime.now().timetuple()
# time.struct_time(tm_year=2018, tm_mon=12, tm_mday=21, tm_hour=20, tm_min=35, tm_sec=1, tm_wday=4, tm_yday=355, tm_isdst=-1)

3、datetime.timedelta

datetime.timedelta用于计算两个日期之间的差值

datetime.timedelta(weeks=1)  # 返回一个时间差,参数weeks,days,hours,minutes,seconds [1 weeks=7 days],没有years,months

例1:
import datetime
day7 = datetime.timedelta(days=7)  # 7天的时间时间隔  一年用52周表示 weeks=52
today = datetime.datetime.now()
# 7天之后的时间是什么
# today + 7
after_7 = today + day7
print(after_7, type(after_7))


例2:
time1 = datetime.datetime(2018, 12, 20, 10, 24, 8)
time2 = datetime.datetime(2017, 11, 12, 10, 24, 0)

"""计算天数差值"""
print((time1 - time2).days)  # 403

"""计算两个日期之间相隔的秒数"""
print((time1 - time2).seconds)  # 8
print((time1 - time2).total_seconds())  # 34819208.0

4、datetime.time

time类有5个参数,datetime.time(hour,minute,second,microsecond,tzoninfo),返回08:29:30

1.datetime.time.replace()

2.datetime.time.strftime(format):按照format格式返回时间

3.datetime.time.tzname():返回时区名字

4.datetime.time.utcoffset():返回时区的时间偏移量

三、时间工具dateutil

直接看例子感受时间工具的绝对时间relativedelta吧

"""pip install python-dateutil"""

from dateutil import relativedelta
import datetime

now = datetime.datetime.today()
print(now)  # 2018-12-21 20:37:31.005604

# 下个月
next_month = now + relativedelta.relativedelta(months=1)
print(next_month)  # 2019-01-21 20:37:31.005604


# 注意months和month的区别:
# months=1 表示在现在的日期基础上加一个月的时间
# months=-1表示在现在的日期基础上减一个月
# month=1 表示把现在的日期的月份设置为1月
# years, months, days, weeks, hours, minutes, seconds等也是跟对应的year,month,day,week...一样
set_month = now + relativedelta.relativedelta(month=1)
print(set_month)  # 2018-01-21 20:37:31.005604(今天是12月21)


# 注意与datetime.timedelta区别:
# datetime.timedelta没有months和years参数
# 因此一个月用weeks=4表示,只能表示28天后,有偏差
next_month2 = now + datetime.timedelta(weeks=4)
print(next_month2)  # 2019-01-18 20:37:31.005604


# 下个月加一周
next_month_week = now + relativedelta.relativedelta(months=1, weeks=1)
print(next_month_week)  # 2019-01-28 20:37:31.005604


# 下个月加一周,上午10点
next_month_week_ten = now + relativedelta.relativedelta(months=1, weeks=1, hour=10)
print(next_month_week_ten)  # 2019-01-28 10:37:31.005604


# 一年后的前一个月
next_year_premonth = now + relativedelta.relativedelta(years=1, months=-1)
print(next_year_premonth)  # 2019-11-21 20:37:31.005604
原文地址:https://www.cnblogs.com/Zzbj/p/10156501.html