关于python显示日期函数的信息( 二 )


获取格式化的时间
你可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime():
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
localtime = time.asctime( time.localtime(time.time()) )
print "本地时间为 :", localtime
以上实例输出结果:
本地时间为 : Thu Apr7 10:05:21 2016
格式化日期
我们可以使用 time 模块的 strftime 方法来格式化日期,:
time.strftime(format[, t])
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
# 格式化成2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 格式化成Sat Mar 28 22:24:24 2016形式
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
以上实例输出结果:
2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0
python中时间日期格式化符号:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
获取某月日历
Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import calendar
cal = calendar.month(2016, 1)
print "以下输出2016年1月份的日历:"
print cal;
以上实例输出结果:
以下输出2016年1月份的日历:
January 2016
Mo Tu We Th Fr Sa Su
123
456789 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Time 模块
Time 模块包含了以下内置函数,既有时间处理相的,也有转换时间格式的:
序号
函数及描述
1time.altzone
返回格林威治西部的夏令时地区的偏移秒数 。如果该地区在格林威治东部会返回负值(如西欧,包括英国) 。对夏令时启用地区才能使用 。
2time.asctime([tupletime])
接受时间元组并返回一个可读的形式为"Tue Dec 11 18:07:14 2008"(2008年12月11日 周二18时07分14秒)的24个字符的字符串 。
3time.clock( )
用以浮点数计算的秒数返回当前的CPU时间 。用来衡量不同程序的耗时,比time.time()更有用 。
4time.ctime([secs])
作用相当于asctime(localtime(secs)) , 未给参数相当于asctime()
5time.gmtime([secs])
接收时间?。?970纪元后经过的浮点秒数)并返回格林威治天文时间下的时间元组t 。注:t.tm_isdst始终为0
6time.localtime([secs])
接收时间?。?970纪元后经过的浮点秒数)并返回当地时间下的时间元组t(t.tm_isdst可取0或1 , 取决于当地当时是不是夏令时) 。
7time.mktime(tupletime)
接受时间元组并返回时间?。?970纪元后经过的浮点秒数) 。
8time.sleep(secs)
推迟调用线程的运行 , secs指秒数 。
9time.strftime(fmt[,tupletime])

推荐阅读