您的位置:首页 > 编程语言 > Python开发

python模块系列之 - time,datetime,calendar

2016-01-26 16:29 721 查看

time模块

localtime

当前时间的struct_time形式

>>> time.localtime()
time.struct_time(tm_year=2015, tm_mon=2, tm_mday=2, tm_hour=16, tm_min=33, tm_sec=36, tm_wday=0, tm_yday=33, tm_isdst=0)

ctime

当前时间的字符串形式

>>> time.ctime()
'Mon Feb 02 16:44:42 2015'

time

获取当前时间戳

>>> time.time()
1422866775.002

strftime

格式化时间( strftime(format[, tuple]) -> string 返回字符串 )

>>> time.strftime('%Y%m%d %X',time.localtime())
'20150202 16:20:19'
对于参数说明argue:

将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出

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 当前时区的名称

%% %号本身

strptime

将字符串格式化为时间(strptime(string, format) -> struct_time )

>>> strtime='2015-02-02 16:42:05'
>>> time.strptime(strtime,'%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2015, tm_mon=2, tm_mday=2, tm_hour=16, tm_min=42, tm_sec=5, tm_wday=0, tm_yday=33, tm_isdst=-1)

mktime

将格式字符串转换为时间戳
>>> a = '2015-02-02 16:42:05'
>>> b = time.mktime(time.strptime(a,"%Y-%m-%d %H:%M:%S"))
>>> b
1422866525.0


datetime

datetimes模块包含一些函数和类,单独或联合使用来解决日常的日期和时间

time

time(hour,min,second) 可以用来验证时间是否正确,如果hour、min、second 数字都有效则返回一个datetime.time类,
from datetime import time
a = time(12,23,30)
print("type of a:", type(a))        # type of a: <class 'datetime.time'>
print(a)                            # 12:23:30
print("hour:{0}  min:{1}  second:{2}".format(a.hour,a.minute,a.second))  # hour:12  min:23  second:30
error_a = time(24,30,30)
print(error_a)                      # ValueError: hour must be in 0..23  可以通过time的方法来获取时间是否有效


时间time函数实例只能拥有时间值,不包含与时间相关的日期,通过time的min,max,可以获取时间的范围
print('Earliest  :', time.min)         # 最早时间  : 00:00:00
print('Latest    :', time.max)         # 最晚时间    : 23:59:59.999999
print('Resolution:', time.resolution)  # 最小单位: 0:00:00.000001

dates

日历日期表示的值都是通过date类来表示的,实例拥有 year, month, 和day属性,你可以很容易的通过today()方法来创建一个今天的日期

from datetime import date

today = date.today()
print(':',today)
print('ctime:', today.ctime())
print('tuple:', today.timetuple())
print('ordinal:', today.toordinal())
print('Year:', today.year)
print('Mon :', today.month)
print('Day :', today.day)
运行结果:
today: 2016-01-26
ctime: Tue Jan 26 00:00:00 2016
tuple: time.struct_time(tm_year=2016, tm_mon=1, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=26, tm_isdst=-1)
ordinal: 735989
Year: 2016
Mon : 1
Day : 26
date 也有一个大小范围值,通过以下方法获取date的大小区间
print('Earliest  :', date.min)           # 最早日期  : 0001-01-01
print('Latest    :', date.max)           # 最晚日期    : 9999-12-31
print('Resolution:', date.resolution)    # 最小单位: 1 day, 0:00:00

replace

另一种获取日期实例的方法是通过replace()方法和一个已经存在的日期,你可以保留月和日不变,只改变年份,比如:
from datetime import date
d1 = date(2008, 3, 12)
print('d1:', d1)   # d1: 2008-03-12

d2 = d1.replace(year=2009)
print('d2:', d2)   # d2: 2009-03-12

d3 = date(2016,13,25)
print("error_date:",d3)  # ValueError: month must be in 1..12  通过date方法就可直接判断输入的一个日期是否有效

timedeltas

使用 replace() 并不是唯一的方法来计算 将来/过去 的日期,你可以通过timedelta类来执行一个日期的基本算数.通过timedelta可以用来添加或减去一个日期来产生另一个日期。用来作为加减运算的内部值可以是 days、seconds和microseconds。几日增加用整数,日期减用负数

import datetime
curr_time = datetime.datetime.now()
print("current time:",curr_time)
print("microseconds:", curr_time + datetime.timedelta(microseconds=1))
print("milliseconds:", curr_time + datetime.timedelta(milliseconds=1))
print("seconds     :", curr_time + datetime.timedelta(seconds=1))
print("minutes     :", curr_time + datetime.timedelta(minutes=1))
print("hours       :", curr_time + datetime.timedelta(hours=1))
print("days        :", curr_time + datetime.timedelta(days=1))
print("weeks       :", curr_time + datetime.timedelta(weeks=1))
运行结果:
current time: 2016-01-26 15:57:06.977737
microseconds: 2016-01-26 15:57:06.977738
milliseconds: 2016-01-26 15:57:06.978737
seconds     : 2016-01-26 15:57:07.977737
minutes     : 2016-01-26 15:58:06.977737
hours       : 2016-01-26 16:57:06.977737
days        : 2016-01-27 15:57:06.977737
weeks       : 2016-02-02 15:57:06.977737


日期算数运算

import datetime
print("今天:",datetime.date.today())
print("昨天:",datetime.date.today() - datetime.timedelta(days=1))
print("明天:",datetime.date.today() + datetime.timedelta(days=1))

日期与时间的结合

import datetime

print('Now    :', datetime.datetime.now())
print('Today  :', datetime.datetime.today())
print('UTC Now:', datetime.datetime.utcnow())

d = datetime.datetime.now()
for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
    print(attr, ':', getattr(d, attr))
# 结果:
Today  : 2016-01-26 16:09:21.731762
UTC Now: 2016-01-26 08:09:21.731763
year : 2016
month : 1
day : 26
hour : 16
minute : 9
second : 21
microsecond : 731763


calendar

calendar是一个定义了一个日历类,,封装了一个月或年的日期和星期,另外,也可以展示文本日历和HTML日历的格式输出
import calendar

c = calendar.TextCalendar(calendar.SUNDAY)
c.prmonth(2016, 1)

January 2016
Su Mo Tu We Th Fr Sa
1  2
3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31


也可以返回HTML
c = calendar.HTMLCalendar(calendar.SUNDAY)
print(c.formatmonth(2016, 1))
运行结果
<table border="0" cellpadding="0" cellspacing="0" class="month">
<tr><th colspan="7" class="month">January 2016</th></tr>
<tr><th class="sun">Sun</th><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th></tr>
<tr><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="fri">1</td><td class="sat">2</td></tr>
<tr><td class="sun">3</td><td class="mon">4</td><td class="tue">5</td><td class="wed">6</td><td class="thu">7</td><td class="fri">8</td><td class="sat">9</td></tr>
<tr><td class="sun">10</td><td class="mon">11</td><td class="tue">12</td><td class="wed">13</td><td class="thu">14</td><td class="fri">15</td><td class="sat">16</td></tr>
<tr><td class="sun">17</td><td class="mon">18</td><td class="tue">19</td><td class="wed">20</td><td class="thu">21</td><td class="fri">22</td><td class="sat">23</td></tr>
<tr><td class="sun">24</td><td class="mon">25</td><td class="tue">26</td><td class="wed">27</td><td class="thu">28</td><td class="fri">29</td><td class="sat">30</td></tr>
<tr><td class="sun">31</td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td><td class="noday"> </td></tr>
</table>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: