python之时间函数

import time

print(time.clock())
print(time.process_time())
print(time.time()) #返回当前系统时间戳
print(time.ctime()) #返回当前系统时间
print(time.ctime(time.time()-86640)) #将时间戳转为字符串
print(time.gmtime(time.time()-86640)) #将时间戳转为struct_time格式
print(time.localtime(time.time()-86640)) #将时间戳转为struct_time格式,但返回本地赶时间
print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time转回时间戳
#time.sleep(1) #睡眠4秒
print(time.strftime("%Y-%m-%d %H:%M:%S"),time.gmtime())#将struct_time转成指定字符串格式
print(time.strptime("2016-01-28","%Y-%m-%d")) #字符串格式转成struct_time

import datetime

print(datetime.date.today()) #输出格式 2016-05-25
print(datetime.date.fromtimestamp(time.time() - 864400)) #将时间戳转成日期格式
current_time = datetime.datetime.now()
print(current_time) #输出2016-05-25 19:33:49.521486
print(current_time.timetuple()) #返回struct_time格式
print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换
str_to_date = datetime.datetime.strptime("2016-05-25 19:42:00","%Y-%m-%d %H:%M:%S") #将字符串转换成日期格式
new_date = datetime.datetime.now() + datetime.timedelta(days=10)
new_date = datetime.datetime.now() + datetime.timedelta(days=-10)
new_date = datetime.datetime.now() + datetime.timedelta(hours=-10)
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120)

最常用的几个时间函数:
time.time():返回当前的时间戳
time.localtime([secs]):默认将当前时间戳转换成当前时区的struct_time
time.sleep([secs]):计时器
time.strftime(format,[,t]):把一个struct_time转换成格式化的时间字符串

函数支持的格式化函数如下:

参数

函义

   

%a

本地简化星期名

%A

本地完整星期名

%b

本地简化月名

%B

本地完整月名称

%c

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

%d

一个月中的第几天

%H

一天中的第几个小时(24小时制,00-23)

%I

(12小时制01-12)

%j

一年中的第几天(001-366)

%m

月份

%M

分钟数

%p

本地am或者pm的响应值

%S

%U

一年中的星期数

%w

一星期中的第几天(0-6,0是星期天)

%W

和%U基本相同,不同的是它是以星期一为一个星期的开始

%x

本地相应的日期

%X

本地相应的时间

%y

简化的年份(00-99)

%Y

完年份

%Z

时区的名字

%%

%字符



原文地址:https://www.cnblogs.com/kongzhagen/p/5528295.html