time和datetime模块的常用方法
time模块
方法 | 作用 |
---|---|
time.time() | 返回当前时间的时间戳、 |
time.clock() | cpu工作时间,Python 3.8 已移除 clock() 方法 可以使用 time.perf_counter() 或 time.process_time() 方法替代。 |
time.gmtime() | 将时间戳类型的时间转换为UTC中的struct_time,参数为时间戳类型,不 |
time.localtime() | 本地时间 |
time.strftime(’%Y-%m-%d %H:%M:%S’, time.localtime()) | 以格式返回本地时间 |
time.strptime(‘2020-10-21 19:49:29’, ‘%Y-%m-%d %H:%M:%S’) | 根据所给的格式把一个时间字符串解析为时间元组。 |
time.mktime(struct_time) | 将struct_time类型的时间转换为时间戳类型。参数:struct_time类型的时间。 |
time.ctime() | 将时间戳的时间转换为表示本地时间的字符串。如果不填参数默认为当前时间的时间戳。 |
time.sleep(t) | 将程序推迟t秒钟执行 |
datetime模块
- datatime模块重新封装了time模块,提供更多接口,提供的类有:date,time,datetime,timedelta,tzinfo。
date类
方法 | 作用 |
---|---|
date.max、date.min | date对象所能表示的最大、最小日期; |
date.resolution | date对象表示日期的最小单位。这里是天。 |
date.today() | 返回一个表示当前本地日期的date对象; |
date.fromtimestamp(timestamp) | 根据给定的时间戮,返回一个date对象; |
date.year、date.month、date.day | 年、月、日; |
date.replace(year, month, day) | 生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变) |
date.timetuple() | 返回日期对应的time.struct_time对象; |
date.weekday() | 返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推; |
date.isoweekday() | 返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推; |
date.isocalendar() | 以元组(iso year, iso_week, iso_weekday)的形式返回日期, 这里的iso_week范围在1到53之间, iso_weekday围在1(星期一)到7(星期日)之间。 |
date.isoformat() | 返回格式如’YYYY-MM-DD’的字符串; |
date.strftime(fmt) | 和time模块format相同。 |
import time
from datetime import date
print(date.max)
print(date.min)
print(date.today())
print(date.fromtimestamp(time.time()))
运行结果:
9999-12-31
0001-01-01
2020-10-21
2020-10-21
from datetime import *
now = date(2020, 10, 21)
tomorrow = now.replace(day = 22)
print('now:', now, ', tomorrow:', tomorrow)
print('timetuple():', now.timetuple())
print('weekday():', now.weekday())
print('isoweekday():', now.isoweekday())
print('isocalendar():', now.isocalendar())
print('isoformat():', now.isoformat())
print('strftime():', now.strftime("%Y-%m-%d"))
运行结果:
now: 2020-10-21 , tomorrow: 2020-10-22
timetuple(): time.struct_time(tm_year=2020, tm_mon=10, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=295, tm_isdst=-1)
weekday(): 2
isoweekday(): 3
isocalendar(): (2020, 43, 3)
isoformat(): 2020-10-21
strftime(): 2020-10-21
time类
方法 | 作用 |
---|---|
time.min、time.max | time类所能表示的最小、最大时间。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999); |
time.resolution | 时间的最小单位,这里是1微秒; |
time(10,23,15) | time对象 |
time.hour time.minute time.second time.microsecond | 时、分、秒、微秒; |
time.tzinfo | 时区信息; |
time.replace([ hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ) | 创建一个新的时间对象,用参数指定的时、分、秒、微秒代替原有对象中的属性(原有对象仍保持不变); |
time.isoformat() | 返回型如"HH:MM:SS"格式的字符串表示; |
time.strftime(fmt) | 同time模块中的format; |
from datetime import *
tm = time(23, 46, 10)
print('tm:', tm)
print('hour: %d, minute: %d, second: %d, microsecond: %d' % (tm.hour, tm.minute, tm.second, tm.microsecond))
tm1 = tm.replace(hour=20)
print('tm1:', tm1)
print('isoformat():', tm.isoformat())
print('strftime()', tm.strftime("%X"))
运行结果:
tm: 23:46:10
hour: 23, minute: 46, second: 10, microsecond: 0
tm1: 20:46:10
isoformat(): 23:46:10
strftime() 23:46:10
datetime类
- datetime相当于date和time结合起来。 datetime.datetime (year, month, day[ ,
hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] )
方法 | 作用 |
---|---|
datetime.today() | 返回一个表示当前本地时间的datetime对象; |
datetime.now([tz]) | 返回一个表示当前本地时间的datetime对象,如果提供了参数tz,则获取tz参数所指时区的本地时间; |
datetime.utcnow() | 返回一个当前utc时间的datetime对象;#格林威治时间 |
datetime.fromtimestamp(timestamp[, tz]) | 根据时间戮创建一个datetime对象,参数tz指定时区信息; |
datetime.utcfromtimestamp(timestamp) | 根据时间戮创建一个datetime对象; |
datetime.combine(date, time) | 根据date和time,创建一个datetime对象; |
datetime.strptime(date_string, format) | 将格式字符串转换为datetime对象; |
dt=datetime.now() | datetime对象 |
dt.year、dt.month、dt.day、dt.hour、dt.minute、dt.second、dt.microsecond、dt.tzinfo | 获取年,月,日,时,分,秒,微秒,时区信息 |
dt.date() | 获取date对象; |
dt.time() | 获取time对象; |
dt. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]) | 创建一个新的时间对象,用参数指定的年、月、日、时、分、秒、微秒代替原有对象中的属性(原有对象仍保持不变); |
dt. timetuple () | 返回日期对应的time.struct_time对象; |
dt. utctimetuple () | 返回一个utc时间的time.struct_time对象;#格林威治时间 |
dt. toordinal () | 计算从1-1-1年开始到现在一共多少天,1-1-1算作第一天 |
dt. weekday () | 返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推; |
dt.isoweekday () | 和weekday类似,不过星期一,返回1;星期2,返回2,以此类推 |
dt. isocalendar () | 以元组(iso year, iso_week, iso_weekday)的形式返回日期, 这里的iso_week范围在1到53之间, iso_weekday围在1(星期一)到7(星期日)之间。 |
dt.fromisocalendar(year, week, day) | 返回以 year, week 和 day 值指明的 ISO 历法日期所对应的 datetime。 该datetime 对象的非日期部分将使用其标准默认值来填充。 这是函数 datetime.isocalendar() 的逆操作。官方文档解释说是3.7版本以后就有,但是实测3.7.3并没有,所以建议至少在3.8以后使用 |
dt. isoformat ([ sep] ) | 返回格式如’YYYY-MM-DDTHH:MM:SS.’的字符串(后面还带有微秒,但是微秒的结构化表示我暂时没找到); |
dt. ctime () | 返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple())); |
dt. strftime (format) |
from datetime import *
import time
print('datetime.max:', datetime.max)
print('datetime.min:', datetime.min)
print('datetime.resolution:', datetime.resolution)
print('today():', datetime.today())
print('now():', datetime.now())
print('utcnow():', datetime.utcnow())
print('fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()))
print('utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time()))
运行结果:
datetime.max: 9999-12-31 23:59:59.999999
datetime.min: 0001-01-01 00:00:00
datetime.resolution: 0:00:00.000001
today(): 2020-10-22 10:01:00.663665
now(): 2020-10-22 10:01:00.663665
utcnow(): 2020-10-22 02:01:00.663665
fromtimestamp(tmstmp): 2020-10-22 10:01:00.663665
utcfromtimestamp(tmstmp): 2020-10-22 02:01:00.663665
from datetime import datetime
dt = datetime.now()
print('dt:', dt)
print('year:', dt.year)
print('month:', dt.month)
print('day:', dt.day)
print('hour:', dt.hour)
print('minute:', dt.minute)
print('second:', dt.second)
print('microsecond:', dt.microsecond)
print('tzinfo:', dt.tzinfo)
print('date:', dt.date())
print('time:', dt.time())
dt1 = dt.replace(hour=20)
print('dt1:', dt1)
print('timetuple:', dt.timetuple())
print('utctimetuple:', dt.utctimetuple())
dt2 = datetime(1, 1, 1, 0, 0, 0, 0)
print('toordinal_dt2:', dt2.toordinal())
print('toordinal_dt:', dt.toordinal())
print('weekday:', dt.weekday())
print('isoweekday:', dt.isoweekday())
print('isocalendar:', dt.isocalendar())
print('isoformat:', dt.isoformat())
print('ctime:', dt.ctime())
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
运行结果:
dt: 2020-10-22 11:01:13.640343
year: 2020
month: 10
day: 22
hour: 11
minute: 1
second: 13
microsecond: 640343
tzinfo: None
date: 2020-10-22
time: 11:01:13.640343
dt1: 2020-10-22 20:01:13.640343
timetuple: time.struct_time(tm_year=2020, tm_mon=10, tm_mday=22, tm_hour=11, tm_min=1, tm_sec=13, tm_wday=3, tm_yday=296, tm_isdst=-1)
utctimetuple: time.struct_time(tm_year=2020, tm_mon=10, tm_mday=22, tm_hour=11, tm_min=1, tm_sec=13, tm_wday=3, tm_yday=296, tm_isdst=0)
toordinal_dt2: 1
toordinal_dt: 737720
weekday: 3
isoweekday: 4
isocalendar: (2020, 43, 4)
isoformat: 2020-10-22T11:01:13.640343
ctime: Thu Oct 22 11:01:13 2020
strftime: 2020-10-22 11:01:13
timedelta类,时间加减
- 使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法。
from datetime import *
dt = datetime.now()
print("dt:", dt)
dt1 = dt + timedelta(days=-1)
dt2 = dt - timedelta(days=1)
dt3 = dt + timedelta(days=1)
print("dt1:", dt1)
print("dt2:", dt2)
print("dt3:", dt3)
delta_obj = dt3 - dt
print("type:", type(delta_obj), "delta_obj:", delta_obj)
print("delta_obj.days:", delta_obj.days, "delta_obj.total_seconds():", delta_obj.total_seconds())
运行结果:
dt: 2020-10-22 11:08:13.414766
dt1: 2020-10-21 11:08:13.414766
dt2: 2020-10-21 11:08:13.414766
dt3: 2020-10-23 11:08:13.414766
type: <class 'datetime.timedelta'> delta_obj: 1 day, 0:00:00
delta_obj.days: 1 delta_obj.total_seconds(): 86400.0
tzinfo时区类
from datetime import datetime, tzinfo, timedelta
"""
tzinfo是关于时区信息的类
tzinfo是一个抽象类,所以不能直接被实例化
"""
class UTC(tzinfo):
"""UTC"""
def __init__(self, offset=0):
self._offset = offset
def utcoffset(self, dt):
return timedelta(hours=self._offset)
def tzname(self, dt):
return "UTC +%s" % self._offset
def dst(self, dt):
return timedelta(hours=self._offset)
# 北京时间
beijing = datetime(2011, 11, 11, 0, 0, 0, tzinfo=UTC(8))
print("beijing time:", beijing)
# 曼谷时间
bangkok = datetime(2011, 11, 11, 0, 0, 0, tzinfo=UTC(7))
print("bangkok time", bangkok)
# 北京时间转成曼谷时间
print("beijing-time to bangkok-time:", beijing.astimezone(UTC(7)))
# 计算时间差时也会考虑时区的问题
timespan = beijing - bangkok
print("时差:", timespan)
运行结果:
beijing time: 2011-11-11 00:00:00+08:00
bangkok time 2011-11-11 00:00:00+07:00
beijing-time to bangkok-time: 2011-11-10 23:00:00+07:00
时差: -1 day, 23:00:00
time模块中时间表现的格式主要有三种:
- timestamp时间戳,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量
- struct_time时间元组,共有九个元素组。
- format time 格式化时间,已格式化的结构使时间更具可读性。包括自定义格式和固定格式。
时间格式转换图
struct_time元组元素结构
属性 | 值 |
---|---|
tm_year(年) | 比如2011 |
tm_mon(月) | 1 - 12 |
tm_mday(日) | 1 - 31 |
tm_hour(时) | 0 - 23 |
tm_min(分) | 0 - 59 |
tm_sec(秒) | 0 - 61 |
tm_wday(weekday) | 0 - 6(0表示周日) |
tm_yday(一年中的第几天) | 1 - 366 |
tm_isdst(是否是夏令时) | 默认为-1 |
format time结构化表示
格式 | 含义 |
---|---|
%a | 本地(locale)简化星期名称 |
%A | 本地完整星期名称 |
%b | 本地简化月份名称 |
%B | 本地完整月份名称 |
%c | 本地相应的日期和时间表示 |
%d | 一个月中的第几天(01 - 31) |
%H | 一天中的第几个小时(24小时制,00 - 23) |
%I | 第几个小时(12小时制,01 - 12) |
%j | 一年中的第几天(001 - 366) |
%m | 月份(01 - 12) |
%M | 分钟数(00 - 59) |
%p | 本地am或者pm的相应符 |
%S | 秒(01 - 59) |
%U | 以补零后的十进制数表示的一年中的周序号(星期日作为每周的第一天)。 在新的一年中第一个星期日之前的所有日子都被视为是在第 0 周。(00, 01, …, 53) |
%w | 一个星期中的第几天(0 - 6,0是星期天) |
%W | 以十进制数表示的一年中的周序号(星期一作为每周的第一天)。 在新的一年中第一个第期一之前的所有日子都被视为是在第 0 周。(00, 01, …, 53) |
%x | 本地相应日期 |
%X | 本地相应时间 |
%y | 去掉世纪的年份(00 - 99) |
%Y | 完整的年份 |
%Z | 时区的名字(如果不存在为空字符) |
%% | ‘%’字符 |