Python时间和日期操作需要用到datetime和time标准库模块。
一、time模块
1.time模块表示时间的方式
①时间戳
②格式化的时间字符串
③以数组的形式表示,即(struct_time),共有九个元素
- year (four digits, e.g. 1998)
- month (1-12)
- day (1-31)
- hours (0-23)
- minutes (0-59)
- seconds (0-59)
- weekday (0-6, Monday is 0)
- Julian day (day in the year, 1-366)
- DST (Daylight Savings Time) flag (-1, 0 or 1) 是否是夏令时
2.常用函数
asctime([tuple])
-> string
将一个struct_time(默认为当时时间),转换成字符串。
>>> time.asctime()
'Sun Jul 31 11:10:39 2016'
>>> import time
>>> thisTime = "2016-07-31 12:12:12"
>>> timeTuple = time.strptime(thisTime, "%Y-%m-%d %H:%M:%S")
>>> time.asctime(timeTuple)
'Sun Jul 31 12:12:12 2016'
ctime(seconds)
-> string
将一个时间戳(默认为当前时间)转换成一个时间字符串。
>>> time.ctime()
'Sun Jul 31 11:11:33 2016'
>>> time.ctime(1469938332)
'Sun Jul 31 12:12:12 2016'
strftime(format[, tuple])
-> string
将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出。
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2016-07-31 11:20:41'
>>> import time
>>> thisTime = "2016-07-31 12:12:12"
>>> timeTuple = time.strptime(thisTime, "%Y-%m-%d %H:%M:%S")
>>> time.strftime("%Y-%m-%d %H:%M:%S",timeTuple)
'2016-07-31 12:12:12'
strptime(string, format)
-> struct_time
将时间字符串根据指定的格式化符转换成数组形式的时间。
>>> import time
>>> thisTime = "2016-07-31 12:12:12"
>>> timeTuple = time.strptime(thisTime, "%Y-%m-%d %H:%M:%S")
>>> print timeTuple
time.struct_time(tm_year=2016, tm_mon=7, tm_mday=31, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=6, tm_yday=213, tm_isdst=-1)
time()
-> floating point number
返回当前时间的时间戳。
>>> time.time()
1469935566.776
二、datetime模块
1.datetime中的常量
-
datetime.MINYEAR
,表示datetime所能表示的最小年份,MINYEAR = 1。 -
datetime.MAXYEAR
,表示datetime所能表示的最大年份,MAXYEAR = 9999
2.datetime中的类
- datetime.date:表示日期的类。常用的属性有year, month, day;
- datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond;
- datetime.datetime:表示日期时间。
- datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
- datetime.tzinfo:与时区有关的相关信息。
3.date类
date类表示一个由年、月、日组成的日期。
①类方法与类属性
date类定义了一些常用的类方法与类属性,方便我们操作:
- date.max、date.min:date对象所能表示的最大、最小日期;
- date.resolution:date对象表示日期的最小单位。这里是天。
-
date.today()
:返回一个表示当前本地日期的date对象;
from datetime import date
print(date.today()) #datetime.date(2019, 11, 12)
print(type(date.today())) #<class 'datetime.date'>
#可以转化为字符串格式的,进行分割等字符串的相关操作
print(str(date.today())) #'2019-11-12'
②实例方法和属性
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):自定义格式化字符串。在下面详细讲解。
③date支持的其他操作
- date2 = date1 + timedelta #日期加上一个间隔,返回一个新的日期对象)
- date2 = date1 - timedelta #日期隔去间隔,返回一个新的日期对象
- timedelta = date1 - date2 #两个日期相减,返回一个时间间隔对象
- date1 < date2 #两个日期进行比较
date1 , date2 要是这样的时间格式
datetime.date(year, month, day)
将天数转化为日期格式:
start_time=datetime.date(2017, 12, 31)
day_list = [start_time+ datetime.timedelta(days=i) for i in days]
4.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):返回自定义格式化字符串。在下面详细介绍;
像date一样,也可以对两个time对象进行比较,或者相减返回一个时间间隔对象。
5.datetime类
datetime是date与time的结合体,包括date与time的所有信息。
6.timedelta与tzinfo类
①timedelta类
datetime.timedelta
对象代表两个时间之间的的时间差,两个date或datetime对象相减时可以返回一个timedelta对象。
timedelta包含数据days、seconds、microseconds,表示天数、秒数、微秒数,包含方法total_seconds() ,表示时间间隔的总秒数。
②tzinfo类
tzinfo:与时区有关的相关信息。
三、常见的日期时间操作
- 更改日期格式
方法:先转换为时间元组,然后转换为其他格式。
>>> import time
>>> thisTime = "2016-07-31 12:12:12"
>>>timeTuple = time.strptime(thisTime, "%Y-%m-%d %H:%M:%S")
>>>otherTime = time.strftime("%Y/%m/%d %H:%M:%S", timeTuple)
>>> print otherTime
2016/07/31 12:12:12
- 将当前时间并转换为指定日期格式
方法一:
>>> import time
>>> nowStamp = int(time.time())
>>> timeTuple = time.localtime(nowStamp)
>>> otherTime = time.strftime("%Y-%m-%d %H:%M:%S", timeTuple)
>>> print otherTime
2016-07-31 10:19:47
方法二:
>>> import datetime
>>> now = datetime.datetime.now()
>>> otherTime = now.strftime("%Y-%m-%d %H:%M:%S")
>>> print otherTime
2016-07-31 10:21:45
- 获取今天、昨天和明天的日期
>>> import datetime
>>> today = datetime.date.today()
>>> yesterday = today - datetime.timedelta(days=1)
>>> tomorrow = today + datetime.timedelta(days=1)
>>> print "昨天:%s, 今天:%s, 明天:%s" % (yesterday, today, tomorrow)
昨天:2016-07-30, 今天:2016-07-31, 明天:2016-08-01
- 获取当前的时间
(1)使用time模块
>>> import time
>>> currentTime = time.strftime("%H:%M:%S")
>>> print currentTime
10:44:30
(2)使用datetime模块
>>> import datetime
>>> now = datetime.datetime.now()
>>> currentTime=str(now.hour)+":"+str(now.minute)+":"+str(now.second)
>>> print currentTime
10:52:18