python基础--time和datetime模块

一:说明
在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。

由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。
UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。
时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
我们运行“type(time.time())”,返回的是float类型。返回时间戳方式的函数主要有time(),clock()等。
元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。
下面列出这种方式元组中的几个元素:

索引(Index) 属性(Attribute) 值(Values)
0 tm_year(年) 比如2011
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 61
6 tm_wday(weekday) 0 - 6(0表示周日)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为-1

二.time使用

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'
import time

print(time.clock())
print(time.process_time())
"""
##返回处理器时间,3.3开始已废弃 ,
改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定
两个方法处理器时间差别很大
结果:
8.552937121372165e-07
0.0780005
"""

print(time.altzone) #返回与UTC(世界统一时间)时间的时间差,以秒计算
print(time.asctime())#返回时间格式“Sat May 13 10:04:47 2017” 美国使用习惯

"""
Python time gmtime() 函数将一个时间戳转换为UTC时区(0时区)的struct_time,可选的参数sec表示从1970-1-1以来的秒数。
其默认值为time.time(),函数返回time.struct_time类型的对象。(struct_time是在time模块中定义的表示时间的对象)。
"""
print(time.localtime())
print(time.gmtime())
print(time.gmtime(time.time()+28800))
"""
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=13, tm_hour=10, tm_min=28, tm_sec=46, tm_wday=5, tm_yday=133, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=13, tm_hour=2, tm_min=28, tm_sec=46, tm_wday=5, tm_yday=133, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=3, tm_hour=20, tm_min=15, tm_sec=26, tm_wday=2, tm_yday=123, tm_isdst=0)
从结果中可以看出time.localtime()与ime.gmtime()差8个时区,即中国与UTC差8个时区,中国是东八区
time.gmtime(time.time()+28800)转和中国时间一样28800=8*60*60秒
"""

print(time.asctime(time.localtime()))#Sat May 13 10:32:45 2017

print(time.ctime())#同上Sat May 13 10:32:45 2017

#把一个格式化时间字符串转化为struct_time
string_2_struct=time.strptime("2017/5/13","%Y/%m/%d")
print(string_2_struct)

#把struct_time转化为格式化的时间字符串
print(time.strftime("%Y/%m/%d",string_2_struct))

#把struct_time转化为时间戳
struct_2_stamp=time.mktime(string_2_struct)
print(struct_2_stamp)

#把时间戳转化为struct_time
print(time.gmtime(struct_2_stamp))
# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

import time

print(time.asctime())
str_2_stuct=time.strptime("Sat May 27 11:20:52 2017","%a %b %d %H:%M:%S %Y") #将字符串时间转struct_time
print(str_2_stuct)
print(time.asctime(str_2_stuct)) #将struct_time转字符串时间,但是返回的美国习惯,如果要自定义字符串格式 使用strftime
print(time.strftime("%Y-%m-%d %H:%M:%S",str_2_stuct)) #将struct_time转字符串时间

stuct_2_stack=time.mktime(str_2_stuct)#将struct_time转换为时间戳
print(stuct_2_stack)
print(time.gmtime(stuct_2_stack)) #gmtime函数将一个时间戳转换为UTC时区的struct_time,这里要特别注意,时间差了8个小时
print(time.gmtime(stuct_2_stack+28800))
"""
结果:
Sat May 27 11:35:12 2017
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=27, tm_hour=11, tm_min=20, tm_sec=52, tm_wday=5, tm_yday=147, tm_isdst=-1)
Sat May 27 11:20:52 2017
2017-05-27 11:20:52
1495855252.0
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=27, tm_hour=3, tm_min=20, tm_sec=52, tm_wday=5, tm_yday=147, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=27, tm_hour=11, tm_min=20, tm_sec=52, tm_wday=5, tm_yday=147, tm_isdst=0)
"""

格式化时间字符串,struct_time,时间戳转换关系

三.datetime

datetime模块定义了两个常量:datetime.MINYEAR和datetime.MAXYEAR,分别表示datetime所能表示的最 小、最大年份。

datetime模块定义了下面这几个类:

  • datetime.date:表示日期的类。常用的属性有year, month, day;
  • datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond;
  • datetime.datetime:表示日期时间。
  • datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
  • datetime.tzinfo:与时区有关的相关信息。
1)date

date类表示一个日期。日期由年、月、日组成(地球人都知道~~)。date类的构造函数如下:
class datetime.date(year, month, day):参数的意义就不多作解释了,只是有几点要注意一下:
year的范围是[MINYEAR, MAXYEAR],即[1, 9999];
month的范围是[1, 12]。(月份是从1开始的,不是从0开始的~_~);
day的最大值根据给定的year, month参数来决定。例如闰年2月份有29天;
date类定义了一些常用的类方法与类属性,方便我们操作:
date.max、date.min:date对象所能表示的最大、最小日期;
date.resolution:date对象表示日期的最小单位。这里是天。
date.today():返回一个表示当前本地日期的date对象;
date.fromtimestamp(timestamp):根据给定的时间戮,返回一个date对象
print(datetime.date.min) #最小日期
print(datetime.date.max)#最大日期
print(datetime.date.today())#今天日期
print(datetime.date.fromtimestamp(time.time()))#根据给定的时间戮,返回一个date对象
 date提供的实例方法和属性:

date.year、date.month、date.day:年、月、日;
date.replace(year, month, day):生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)
date.timetuple():返回日期对应的time.struct_time对象;
date.toordinal():返回日期对应的Gregorian Calendar日期;
date.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;
data.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
date.isocalendar():返回格式如(year,month,day)的元组;
date.isoformat():返回格式如'YYYY-MM-DD’的字符串;
date.strftime(fmt):自定义格式化字符串
now=datetime.date(2017,5,13)
tomorrow=now.replace(day=7)
print(now,tomorrow)
print(now.year)
print(now.timetuple())
print(now.weekday())
print(now.isoweekday())
print(now.isocalendar())
print(now.isoformat())
print(now.strftime("%Y/%m/%d"))
date还对某些操作进行了重载,它允许我们对日期进行如下一些操作:
date2 = date1 + timedelta # 日期加上一个间隔,返回一个新的日期对象(timedelta将在下面介绍,表示时间间隔)
date2 = date1 - timedelta # 日期隔去间隔,返回一个新的日期对象
timedelta = date1 - date2 # 两个日期相减,返回一个时间间隔对象
date1 < date2 # 两个日期进行比较
注: 对日期进行操作时,要防止日期超出它所能表示的范围。
print(now-tomorrow)

print(now+datetime.timedelta(11))
print(now>tomorrow)
2)Time类

time类表示时间,由时、分、秒以及微秒组成.
time类定义的类属性:

time.min、time.max:time类所能表示的最小、最大时间。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
time.resolution:时间的最小单位,这里是1微秒;
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):返回自定义格式化字符串

tm=datetime.time(15,5,0)
print(tm)

print(tm.hour,tm.minute,tm.second)
print(tm.tzinfo)
print(tm.replace(hour=1))
print(tm.isoformat())
print(tm.strftime("%H-%M-%S"))
3)datetime类
定义的类属性与方法:

datetime.min、datetime.max:datetime所能表示的最小值与最大值;

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对象
datetime类提供的实例方法与属性(很多属性或方法在date和time中已经出现过,在此有类似的意义,这里只罗列这些方法名,具体含义不再逐个展开介绍,可以参考上文对date与time类的讲解。):

datetime.year、month、day、hour、minute、second、microsecond、tzinfo:
datetime.date():获取date对象;
datetime.time():获取time对象;
datetime. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]):
datetime. timetuple ()
datetime. utctimetuple ()
datetime. toordinal ()
datetime. weekday ()
datetime. isocalendar ()
datetime. isoformat ([ sep] )
datetime. ctime ():返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));
datetime. strftime (format)
today=datetime.datetime.today()
print(today)
print(datetime.datetime.now())
print(datetime.datetime.utcnow())
print(datetime.datetime.fromtimestamp(time.time()))
print(datetime.datetime.combine(now,tm))

4)格式字符串

%a星期的简写。如 星期三为Web
%A星期的全写。如 星期三为Wednesday
%b月份的简写。如4月份为Apr
%B月份的全写。如4月份为April
%c: 日期时间的字符串表示。(如: 04/07/10 10:43:39)
%d: 日在这个月中的天数(是这个月的第几天)
%f: 微秒(范围[0,999999])
%H: 小时(24小时制,[0, 23])
%I: 小时(12小时制,[0, 11])
%j: 日在年中的天数 [001,366](是当年的第几天)
%m: 月份([01,12])
%M: 分钟([00,59])
%p: AM或者PM
%S: 秒(范围为[00,61],为什么不是[00, 59],参考python手册~_~)
%U: 周在当年的周数当年的第几周),星期天作为周的第一天
%w: 今天在这周的天数,范围为[0, 6],6表示星期天
%W: 周在当年的周数(是当年的第几周),星期一作为周的第一天
%x: 日期字符串(如:04/07/10)
%X: 时间字符串(如:10:43:39)
%y: 2个数字表示的年份
%Y: 4个数字表示的年份
%z: 与utc时间的间隔 (如果是本地时间,返回空字符串)
%Z: 时区名称(如果是本地时间,返回空字符串)

原文地址:https://www.cnblogs.com/lixiang1013/p/6848245.html