首页 > 代码库 > python模块之time模块

python模块之time模块

import time

#从1970年1月1号凌晨开始到现在的秒数,是因为这一年unix的第一个商业版本上市了,这个最常用
# print(time.time())

# 1491574950.2398355


#返回当前的系统时间,也可加参数,比如下面的第二个例子
# print(time.ctime())
# print(time.ctime(time.time()-86400))

# Fri Apr 7 22:24:17 2017
# Thu Apr 6 22:25:15 2017



#可以把年、月、日、小时、分钟分别显示出来,但是这里显示的时间是格林威治时间,用下面第二个例子就可以做时间的字符串拼接
# print(time.gmtime())
# time_obj = time.gmtime()
# print(time_obj.tm_year,time_obj.tm_mon)

# time.struct_time(tm_year=2017, tm_mon=4, tm_mday=7, tm_hour=14, tm_min=25, tm_sec=59, tm_wday=4, tm_yday=97, tm_isdst=0)
# 2017 4


#上面显示的格林威治时间,下面这里是显示本地时间
# print(time.localtime())

# time.struct_time(tm_year=2017, tm_mon=4, tm_mday=7, tm_hour=22, tm_min=31, tm_sec=42, tm_wday=4, tm_yday=97, tm_isdst=0)


#把一个时间对象转换成时间戳

# print(time.mktime(time_obj))
# 1491546920.0


#等待10s
# time.sleep(10)
# print(‘wait 10s‘)


#将时间对象转换成指定的字符串格式,参数有两个,分别是格式和时间对象,你可以选择你想要的时间格式,比如就要日期,或者就时间,或者都要

# print(time.strftime("%Y-%m-%d:%H:%M:%S",time.gmtime()))
# 2017-04-07:14:40:28

# print(time.strftime("%Y-%m-%d:%H:%M:%S",time.localtime()))
# 2017-04-07:22:40:50


# ret = time.strptime(‘2016-12-23 15:34:34‘,‘%Y-%m-%d %H:%M:%S‘)
# print(ret)

# time.struct_time(tm_year=2016, tm_mon=12, tm_mday=23, tm_hour=15, tm_min=34, tm_sec=34, tm_wday=4, tm_yday=358, tm_isdst=-1)


import datetime

#显示今天的日期
# print(datetime.date.today())
# 2017-04-07


# ret = datetime.datetime.now()
# print(ret)

# 2017-04-07 22:48:18.861383

#转换time的形式
# print(ret.timetuple())

# time.struct_time(tm_year=2017, tm_mon=4, tm_mday=7, tm_hour=22, tm_min=49, tm_sec=46, tm_wday=4, tm_yday=97, tm_isdst=-1)

#下面介绍下时间的加减

#给当前的时间加10天
# print(datetime.datetime.now() + datetime.timedelta(days=10))
# 2017-04-17 22:55:03.070503


#给当前时间减10天
# print(datetime.datetime.now() + datetime.timedelta(days=-10))
# print(datetime.datetime.now() - datetime.timedelta(days=10))

# 2017-03-28 22:56:08.529247
# 2017-03-28 22:56:08.529247

#上面的例子是加减天,其实timedelta可以支持加减下面的参数,比如周,小时,分钟
# days=0, seconds=0, microseconds=0,milliseconds=0, minutes=0, hours=0, weeks=0):


#
current_time = datetime.datetime.now()
print(current_time)

#替换为某年,某月,某日
print(current_time.replace(2016,1,3))
print(current_time.replace(2016,3))
print(current_time.replace(2015))

# 2016-01-03 23:01:54.095012
# 2016-03-07 23:01:54.095012
# 2015-04-07 23:01:54.095012



#两个时间还可以做比较
# gtime = datetime.datetime.now()
# ctime = gtime.replace(2015)
# if gtime > ctime:
# print(‘true‘)
# else:
# print(‘false‘)

python模块之time模块