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

灰太狼 2022-08-19 15:12 308阅读 0赞

time模块

localtime

当前时间的struct_time形式

  1. >>> time.localtime()
  2. 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

当前时间的字符串形式

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

time

获取当前时间戳

  1. >>> time.time()
  2. 1422866775.002

strftime

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

  1. >>> time.strftime('%Y%m%d %X',time.localtime())
  2. '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 )

  1. >>> strtime='2015-02-02 16:42:05'
  2. >>> time.strptime(strtime,'%Y-%m-%d %H:%M:%S')
  3. 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

将格式字符串转换为时间戳

  1. >>> a = '2015-02-02 16:42:05'
  2. >>> b = time.mktime(time.strptime(a,"%Y-%m-%d %H:%M:%S"))
  3. >>> b
  4. 1422866525.0

datetime

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

time

time(hour,min,second) 可以用来验证时间是否正确,如果hour、min、second 数字都有效则返回一个datetime.time类,

  1. from datetime import time
  2. a = time(12,23,30)
  3. print("type of a:", type(a)) # type of a: <class 'datetime.time'>
  4. print(a) # 12:23:30
  5. print("hour:{0} min:{1} second:{2}".format(a.hour,a.minute,a.second)) # hour:12 min:23 second:30
  6. error_a = time(24,30,30)
  7. print(error_a) # ValueError: hour must be in 0..23 可以通过time的方法来获取时间是否有效

时间time函数实例只能拥有时间值,不包含与时间相关的日期,通过time的min,max,可以获取时间的范围

  1. print('Earliest :', time.min) # 最早时间 : 00:00:00
  2. print('Latest :', time.max) # 最晚时间 : 23:59:59.999999
  3. print('Resolution:', time.resolution) # 最小单位: 0:00:00.000001

dates

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

  1. from datetime import date
  2. today = date.today()
  3. print(':',today)
  4. print('ctime:', today.ctime())
  5. print('tuple:', today.timetuple())
  6. print('ordinal:', today.toordinal())
  7. print('Year:', today.year)
  8. print('Mon :', today.month)
  9. print('Day :', today.day)
  10. 运行结果:
  11. today: 2016-01-26
  12. ctime: Tue Jan 26 00:00:00 2016
  13. 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)
  14. ordinal: 735989
  15. Year: 2016
  16. Mon : 1
  17. Day : 26

date 也有一个大小范围值,通过以下方法获取date的大小区间

  1. print('Earliest :', date.min) # 最早日期 : 0001-01-01
  2. print('Latest :', date.max) # 最晚日期 : 9999-12-31
  3. print('Resolution:', date.resolution) # 最小单位: 1 day, 0:00:00

replace

另一种获取日期实例的方法是通过replace()方法和一个已经存在的日期,你可以保留月和日不变,只改变年份,比如:

  1. from datetime import date
  2. d1 = date(2008, 3, 12)
  3. print('d1:', d1) # d1: 2008-03-12
  4. d2 = d1.replace(year=2009)
  5. print('d2:', d2) # d2: 2009-03-12
  6. d3 = date(2016,13,25)
  7. print("error_date:",d3) # ValueError: month must be in 1..12 通过date方法就可直接判断输入的一个日期是否有效

timedeltas

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

  1. import datetime
  2. curr_time = datetime.datetime.now()
  3. print("current time:",curr_time)
  4. print("microseconds:", curr_time + datetime.timedelta(microseconds=1))
  5. print("milliseconds:", curr_time + datetime.timedelta(milliseconds=1))
  6. print("seconds :", curr_time + datetime.timedelta(seconds=1))
  7. print("minutes :", curr_time + datetime.timedelta(minutes=1))
  8. print("hours :", curr_time + datetime.timedelta(hours=1))
  9. print("days :", curr_time + datetime.timedelta(days=1))
  10. print("weeks :", curr_time + datetime.timedelta(weeks=1))

运行结果:

  1. current time: 2016-01-26 15:57:06.977737
  2. microseconds: 2016-01-26 15:57:06.977738
  3. milliseconds: 2016-01-26 15:57:06.978737
  4. seconds : 2016-01-26 15:57:07.977737
  5. minutes : 2016-01-26 15:58:06.977737
  6. hours : 2016-01-26 16:57:06.977737
  7. days : 2016-01-27 15:57:06.977737
  8. weeks : 2016-02-02 15:57:06.977737

日期算数运算

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

日期与时间的结合

  1. import datetime
  2. print('Now :', datetime.datetime.now())
  3. print('Today :', datetime.datetime.today())
  4. print('UTC Now:', datetime.datetime.utcnow())
  5. d = datetime.datetime.now()
  6. for attr in [ 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']:
  7. print(attr, ':', getattr(d, attr))
  8. # 结果:
  9. Today : 2016-01-26 16:09:21.731762
  10. UTC Now: 2016-01-26 08:09:21.731763
  11. year : 2016
  12. month : 1
  13. day : 26
  14. hour : 16
  15. minute : 9
  16. second : 21
  17. microsecond : 731763

calendar

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

  1. import calendar
  2. c = calendar.TextCalendar(calendar.SUNDAY)
  3. c.prmonth(2016, 1)
  4. January 2016
  5. Su Mo Tu We Th Fr Sa
  6. 1 2
  7. 3 4 5 6 7 8 9
  8. 10 11 12 13 14 15 16
  9. 17 18 19 20 21 22 23
  10. 24 25 26 27 28 29 30
  11. 31

也可以返回HTML

  1. c = calendar.HTMLCalendar(calendar.SUNDAY)
  2. print(c.formatmonth(2016, 1))

运行结果

  1. <table border="0" cellpadding="0" cellspacing="0" class="month">
  2. <tr><th colspan="7" class="month">January 2016</th></tr>
  3. <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>
  4. <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>
  5. <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>
  6. <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>
  7. <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>
  8. <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>
  9. <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>
  10. </table>

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python模块系列 - subprocess

    subprocess – 创建附加进程 subprocess模块提供了一种一致的方法来创建和处理附加进程,与标准库中的其它模块相比,提供了一个更高级的接口。用于替换如下模块

    相关 python模块系列 - xml

    xml 是现在程序中用到的比较重用的一种数据格式,可以用于不同程序或语言之间的数据交换,python当然也不例外,通过xml模块就可以轻松实现xml文件的读写操作 1.生成一

    相关 python模块系列 - copy

          在python中当定义完或者对一个变量完成赋值以后,在内存中就开辟了一块空间来存储对象。如果要将该对象复制一份给另一个对象就要用到copy模块。       在p